alp123
alp123

Reputation: 189

Make React useEffect only run at initial render and when property changes

I have a useEffect that I want only to be run on the initial render and when a variable changes. That means that I don't want it to be run every time the component rerenders. This is where I'm stuck, this is my current code simplified:

useEffect(() => {
       // Some logic only to be performed when variable changes OR at initial render
    }, [variable]);

Any ideas on how to achieve this?

Upvotes: 1

Views: 4857

Answers (2)

Sakshi
Sakshi

Reputation: 1548

In case you want your useEffect to run on initial render then do it like this:

useEffect(()=>{
// do whatever you want to do here
},[]);

and in case you want it to run on some variable change then:

useEffect(() => {
       // Some logic only to be performed when variable changes OR at initial render
    }, [variable]);
    ```

Upvotes: 0

Hubert Hilczer
Hubert Hilczer

Reputation: 95

You need to conditionally run it on every render, so get rid of the dependency array and add conditions inside your useEffect. Otherwise, you can make 2 useEffects, one with an empty dependency array, and the other with the state variable.

Upvotes: 3

Related Questions