Search code examples
javascriptreactjsreduxeasy-peasy

React listen to 1st state change only


I am using useEffect in react to listen to redux(easy-peasy) state change, but I want to listen to 1st value change only.
Because when my page loads the state has a default value and then API call is made and hence data changes but the API is a polling API, hence it keeps getting the data again and again in a short interval of time. But one of my requirement is to listen only to the 1st API data.

This is what I tried:

1st Approach with empty dependency

useEffect(() => {
        // my code 
    },[])

In this case, I get the default value of my state and not the 1st API response.

2nd Approach with state property in the dependency

useEffect(() => {
        // my code
    },[myState])

In this case, I keep getting the updated response from the API

both of these approaches didn't work for me. So please suggest a better solution.


Solution

  • You can do so using a ref variable and comparing the state with initial state (which could be null, undefined, empty object depending on your implementation):

    const hasRun = useRef(false)
    
    useEffect(() => {
      if (!hasRun.current && myState !== initialState) {
        hasRun.current = true
        // run my code
      }
    },[myState])
    

    A ref variable won't participate in re-rendering.