Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent useEffect hook from running on ComponentDidMount()

This code runs when name is changed (as it should) but it also runs when the component first loads. How can I have it run only on subsequent changes to name and not the first time the default value is set?

const [name, setName] = useState('');

useEffect(() => {
  alert('Hi ' + name);
}, [name]);

1 Answers

Using a ref you can track the first render, set to false after the first render.

const firstRenderRef = useRef(true);
const [name, setName] = useState('');

useEffect(() => {
  if (firstRenderRef.current) {
    firstRenderRef.current = false;
  } else {
    alert('Hi ' + name);
  }
}, [name]);

I'd factor this into a custom hook though

const useSkipFirstEffect = (callback, dependencies) => {
  const firstRenderRef = useRef(true);

  useEffect(() => {
    if (firstRenderRef.current) {
      firstRenderRef.current = false;
    } else {
      callback();
    }
  }, [callback, ...dependencies]);
};

Usage:

useSkipFirstEffect(() => {
  alert('SkipFirstEffect: Hi ' + name);
}, [name]);

Edit useEffect skip first render

like image 112
Drew Reese Avatar answered Dec 02 '25 16:12

Drew Reese