use-next-tick

React Hook

use-next-tick

nextTick for React, used to run callbacks after the DOM or native views have updated.

Why?

Sometimes you need to read layout, measure elements, or access refs right after a state change—but React updates asynchronously. useNextTick gives you a simple way to schedule code that runs after React commits your changes.

npm i use-next-tick
const [count, setCount] = useState(0)
const nextTick = useNextTick();

const handleClick = () => {
  setCount(c => c+1);
  nextTick(() => {
    // Run code after setCount update
  })
}
          

Online Playground

Usage

basic Usage — read DOM after state update
import { useState, useRef } from "react";
import useNextTick from "use-next-tick";

function MyComponent() {
  const [count, setCount] = useState(0);
  const ref = useRef<HTMLSpanElement>(null);
  const nextTick = useNextTick();

  const handleClick = () => {
    setCount((c) => c + 1);
    nextTick(() => {
      console.log(ref.current?.textContent); // "1" ✓
    });
  };

  return <span ref={ref}>{count}</span>;
}
Without next tick — read DOM after state update.
import { useState, useRef } from "react";

function MyComponent() {
  const [count, setCount] = useState(0);
  const ref = useRef<HTMLSpanElement>(null);

  const handleClick = () => {
    setCount((c) => c + 1);
  };

  // We need extra useEffect
  useEffect(() => {
    console.log(ref.current?.textContent);
  }, [count]);

  return <span ref={ref}>{count}</span>;
}

Playground

Click the buttons to see nextTick callbacks read the committed DOM.

Counter

0
  • A
  • B
  • C

Logs

  • No logs yet

Other Projects

xior

Lightweight HTTP request library based on fetch with plugin support and similar API to axios.

tsdk

Type-safe API development CLI tool for TypeScript projects.

broad-infinite-list

High performance and bidirectional scrolling infinite list component for React, Vue 3 and React Native, good for large list rendering.