Search code examples
javascriptreactjsreact-hooksuse-effect

Why is this React.useEffect() code not safe?


I am trying to understand React.useEffect() in the official React tutorial.

There I came across this under the question 'Is it safe to omit functions from the list of dependencies?':

function Example({ someProp }) {
  function doSomething() {
    console.log(someProp);
  }
  useEffect(() => {
    doSomething();
  }, []); // 🔴 This is not safe (it calls `doSomething` which uses `someProp`)
}

The explanation is somewhat limited. Why is it not safe?

Isn't 'props' immutable? Why should it be in the depedencies list?

Also, what 'function' should be there in the list of dependencies? Why is it not called 'props' instead?


Solution

  • The useEffect hook is multipurpose. Its use is not limited to only one. You can use useEffect for

    1. as componentDidMount
    2. as componentReceiveProps
    3. as componenetDidUnmount

    To answer your this questions: what 'function' should be there in the list of dependencies?

    the function which you think are gonna change refereence, or functions whose reference gonna change in future(generally the functions which you receive via props) are meant to go inside dependency list.

    Why is it not called 'props' instead? because dependency is more descriptive about useEffect. as useEffect is dependent on the array. useEffect will be called again and again if anything on the dependency list changes. That's why.

    Isn't 'props' immutable? Why should it be in the depedencies list? so that useEffect know when to re-call itself. So that you can call a method again when prop changes.

    For Example you have a list of product and aside it you are showing description. Not if you only pass id as a prop, your description won't be updated. To update description you may leverage the dependency array,