1

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?

3
  • your code should already work as described ^; could you create a working example where it isn't so that we have help debug Commented Dec 8, 2020 at 17:24
  • It is working, but not as I want.. The problem with that code is that it rerenders every time the component mounts, where I only want it to be run on the initial load. Commented Dec 8, 2020 at 17:26
  • could you add a complete example? if the component is unmounting & remounting - for eg, say you are doing - { isVisible && <YourComponent /> }... & isVisible is changing, i dont think you can prevent this at a hooks level, unless you do some sort of global memoization outside the component Commented Dec 8, 2020 at 17:32

2 Answers 2

3

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.

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

Comments

0

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]);
    ```

1 Comment

The problem is that my component rerenders a lot due to changes in state and use of useMemo etc, so these useEffects will be run on every rerender in my component, where I only want it to run on the initial load/refresh of page (or when variable changes) ...

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.