0

I am having trouble knowing how the useEffect dependency array rules work.

By the docs I see that it tells me, we should include all the props/state/derived vars that are used inside the useEffect.

So let's say we want to execute some code when the param count changes, but access the innerCount value as well. By the docs it states I should add it to the dependencies list to prevent the code from having stale values from previous renders, but technically it will always get the correct value even if I don't pass it in the dependency list...

And also if I do add it to the dependency list, that means I would have to do double validation inside the useEffect just to run that code ONLY when count has changed from its previous value...

function Component({ count }) {
  const [innerCount, setInnerCount] = useState(0);

  useEffect(() => {
    console.log('innerCount', innerCount);
    setInnerCount(innerCount + 1);
  }, [count]);

  return <div>
  <span>Count: {count}</span>
  <span>innerCount: {innerCount}</span>
  </div>;
}

My point is, should I follow react docs and always include all dependencies of the useEffect which adds a lot of complexity? or just ignore it for these cases when stale values will not happen?

1 Answer 1

2

You should always include it, but I know it can be annoying sometimes.

Sign up to request clarification or add additional context in comments.

1 Comment

I will start do include most of the times, but from articles I see this is quite a annoying issue from React, as it tries to fit two definitions into one. Dependencies and Triggers. Theres some open features in React, and the developers state that we should ignore this rule "if we know what we are doing" so I will take that as that the "dependency array" definition is somewhat open to interpretation for developers. Trigger feature What changed feature

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.