Search code examples
reactjsreact-hooksuse-effectreact-contextreact-state

How to differentiate context values if their state changed in React useEffect


const someFunction = () = {
...
const { data, setData, activeIndex, setActiveIndex } = useContext(MusicContext);
 

  
  useEffect(() => {
    console.log(" useEffect called");
    
    // another component called setData or setActiveIndex which resulted here  
    // how to compare data to its prevState if it changed  
    // how to compare activeIndex to its prevState if it changed  

  }, [activeIndex, data]);
...
}

Above is some function which has a useEffect for two different context variables

data is an object proptype {} and activeIndex is a number

how do i compare data to its prevState if it changed?
how do i compare activeIndex to its prevState if it changed?
can i do it in a single useEffect block and need to open multiple?


Solution

  • You can useRef to store the last seen value. This is often extracted into a "usePrevious" custom hook.

    function usePrevious(value) {
      const ref = useRef();
      useEffect(() => {
        ref.current = value;
      });
      return ref.current;
    }
    

    Now in your component, you can check against the previous value.

    const SomeFunction = () = {
      ...
      const { data, setData, activeIndex, setActiveIndex } = useContext(MusicContext);
     
      const prevData = usePrevious( data );
      const prevActiveIndex = usePrevious( activeIndex );
      
      useEffect(() => {
        if ( data !== prevData ) {
          // do something
        }
        if ( activeIndex !== prevActiveIndex ) {
          // do something
        }
    
      }, [activeIndex, data]);
    ...
    }