March 23, 2019

Tutorials

React: run useEffect hook specific times

One of popular new features of react is hooks, which let you use states and other react features within state less components, as a result you will have a cleaner and relatively more reusable code.

one of react’s built in hooks is useEffect() which replaces component life cycle methods into one function. but useEffect runs every time the component is updated but what if we want to run it only once or only when a specific state is updated?

in order to do that we need to pass an array containing name of states that we want use context run when they are updated. we can also pass an empty array to run useContext only once,when component is mounted:

const [count, setCount] = useState(0);

 // run useEffect only when the state "count" is updated
    useEffect(() => {
        console.log(count);
      },[count]);

// run useEffect only once (the first time that component is loaded)
    useEffect(() => {
        alert('welcome')
      },[]);