Venoz
Venoz

Reputation: 75

How to use useEffect with if statement React

I want to add in the dependencies of a useEffect an if statement if a variable is certain value. For example:

let counter = 5;


    useEffect(() => {
        socket.on("counter", counter => {
            setCounter(counter);
        });
        return () => socket.off('counter', counter);
    }, [socket])


useEffect(() => {
//do something
}, counter = 0)

This "counter = 0" in the end is obviously wrong. So how can I run the second useEffect anytime the counter is 0?

Upvotes: 5

Views: 2295

Answers (1)

Brian Thompson
Brian Thompson

Reputation: 14365

You cannot do what you're describing (or at the very least shouldn't), so you just need to move your logic. Instead of only running the useEffect when a variable equals another value, you need to run the useEffect anytime that variable changes and check the value inside the callback.

let counter = 5;


useEffect(() => {
  if (counter == 0) {
    //do something
  }
}, [counter])

Also note that = is always an assignment. To check equality you need == or ===.

Upvotes: 7

Related Questions