Home > Software design >  React usePrevious does not seem to be having previous value
React usePrevious does not seem to be having previous value

Time:11-01

In my React functional components, I am trying to use custom usePrevious to get/compare the previous value of my context object. However, it seems to be having the latest value always and not the previous value. Below is my code. Please let me know if I am doing something wrong here.

function MyHeaderComponent(props) {
    const [myPref, setMyPref] = React.useContext(MyContext);
    const prevPreferences = usePrevious(myPref.preferences);
    
    useEffect(() => {
        console.log("prevPreferences : "   prevPreferences);        // Prints current context object, instead of the previous one
        // I want to call myInfo only if prevPreferences is not the same as myPref.preferences (i.e. current)
    }, [myPref]);
        
    function usePrevious(value) {
        const ref = useRef();
        useEffect(() => {
            ref.current = value;
        });
        return ref.current;
    }    

    const myInfo = async () => {
        setMyPref(myPref);
    }

    return (
        <>
            <div>
                Some JSX
            </div>
        </>
    )
}


export default withRouter(withStyles()(MyHeaderComponent));


function MyPreferences(props) {
    const [myPref, setMyPref] = React.useContext(MyContext);
    
    // somewhere in code
    setMyPref(myPref);                
}

CodePudding user response:

That implementation of useLatest (which should not be within the component, by the way) does not copy the value into the ref box, it just assigns a reference.

I'd wager myPref.preferences gets internally modified (instead of being reassigned a new object), which is why you always see the same value.

CodePudding user response:

I think the problem is you are using usePrevious hook inside another functional component. Could you try to create a file for the usePrevious hook.

usePreviousState.js

function usePrevious(value, initialValue) {
  const ref = useRef();
  useEffect(() => {
    ref.current = value;
  }, [value]);
  if (ref.current === undefined && initialValue !== undefined) {
    return initialValue;
  }
  return ref.current;
}
  • Related