DEV Community

Guru
Guru

Posted on

Run if key changes but not on first render in react

As a developer we might get struck at a place where we do not want to run some specific block of code or some function on the first render of the component in react, and we want to run that function only on some key changes only. As we have useEffect where we specify our dependencies to watch for changes some thing like this

useEffect(() => {
    // the call back function or code if the stateVariable changes
}, [stateVariable]);
Enter fullscreen mode Exit fullscreen mode

As we dont want this above code to run on initial render , we can create a custom hook some thing like this

import React, { useEffect, useRef } from 'react';

const useDidMountEffect = (func, deps) => {
    const didMount = useRef(false);

    useEffect(() => {
        if (didMount.current) func();
        else didMount.current = true;
    }, deps);
}

export default useDidMountEffect;
Enter fullscreen mode Exit fullscreen mode

Usage

To use the above component first we have to import it into the component you want to use

import useDidMountEffect from './path_to_UseDidMountEffect';


useDidMountEffect(() => {
  // react please run me if 'key' changes, but not on initial render
    myFunction()
}, [stateVariable]);

const myFunction = () =>{
   console.log('i am up and running');
}
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
dmarinnaa profile image
dMarina

Nice