useNextTick – React Hook to Run Code After DOM Updates


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(null);
  const nextTick = useNextTick();

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

  return {count};
}

Without next tick — read DOM after state update.

import { useState, useRef } from "react";

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

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

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

  return {count};
}



Source link

Leave a Reply

Your email address will not be published. Required fields are marked *