Affan Shahab
Affan Shahab

Reputation: 888

React hooks loses updated value of state variable inside cleanup function of useEffect

I have this useEffect hook which does something on componentDidMount and want to use it in the end to update my redux store at componentWillUnMount.

const [ordersToCancel, dispatchCancelStatus] = useReducer(cancelReducer, []);

const cancelReducer = (state, action) => {
    //implementation 
}

useEffect(()=>{
    //some Code
    dispatchCancelStatus({ type: "type", state: state });

    return async ()=> {
        const data = ordersToCancel //ordersToCancel is an empty array here as it's default value not the updated one


        //some code
        const results = await api({params})
        dispatch({ type: 'someType', data: data })
    }
}, [])

As mentioned in code snippet, ordersToCancel get reset in cleanup function. I'm making sure this is getting updated. I have another useEffect hook with dependency of ordersToCancel and I can see its getting called and updating the array.

Is it the normal behavior that the state will get reset to default in cleanup function?

Upvotes: 0

Views: 674

Answers (1)

Stéphane Veyret
Stéphane Veyret

Reputation: 1991

You can use useRef to keep an indirect reference to the ordersToCancel variable:

const [ordersToCancel, dispatchCancelStatus] = useReducer(cancelReducer, []);

const ordersToCancelRef = useRef();
ordersToCancelRef.current = ordersToCancel;

const cancelReducer = (state, action) => {
    //implementation 
}

useEffect(()=>{
    //some Code
    dispatchCancelStatus({ type: "type", state: state });

    return async ()=> {
        const data = ordersToCancelRef.current;


        //some code
        const results = await api({params})
        dispatch({ type: 'someType', data: data })
    }
}, [])

Upvotes: 2

Related Questions