4

in what case I shouldn't put the empty array [] as dependcies in react useEffect? like

React.useEffect(() => {
    if (true) {
      doStuff()
    }
    return () => null;
  });

Is above code even valid?

1
  • It's valid. It means the effect runs every time the component re-renders Commented Dec 4, 2020 at 1:01

2 Answers 2

5

just remember 3 rules:

useEffect(()=>{},[]) //this is like componentDidMount
useEffect(()=>{}) //this will run every render
useEffect(()=>{},[dep1, dep2]) //this will run if one on de dependency change
Sign up to request clarification or add additional context in comments.

Comments

3

Your code is valid.

undefined is passed as dependencies and it means useEffect runs on every render. So if you want to do some work that shouldn't be run on every render (like adding event listener), you should give a dependency array.

4 Comments

in what case we put it as undefined?
if you don't give anything (even empty array) as dependency, undefined will be passed.
yeah you already said that, in what case you that?
You can pass nothing If you want to do something every single time the component is updated. But more often than not, you likely only want this effect to happen because of something else. Perhaps you want to do something only when data changes, or maybe when the user first sees the component.

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.