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