79257253

Date: 2024-12-06 08:11:12
Score: 0.5
Natty:
Report link

Based on @Piotr Siupa's answer, I find it more convenient to use it as a callback:

import { useRef } from 'react';

export default function useFirstRender(callback) {
  const ref = useRef(true);

  if (ref.current) {
    callback();
  }

  ref.current = false;
}

In a component:

...

useFirstRender(() => {
  console.log("first");
});

...
Reasons:
  • Has code block (-0.5):
  • User mentioned (1): @Piotr
Posted by: Maksim I. Kuzmin