use-next-tick

React Hook

use-next-tick

A React hook for running 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
Get Started

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

14
  • A
  • B
  • C

Logs

  • tick:1
  • tick:2
  • tick:3
  • tick:4
  • tick:5
  • tick:6
  • tick:7
  • tick:8
  • async:done
  • async:done
  • order:C,B,A
  • order:A,B,C
  • order:C,B,A
  • order:A,B,C
  • chain:1:11
  • chain:2:12
  • chain:1:13
  • chain:2:14

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.