简体   繁体   中英

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?

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 })
    }
}, [])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM