简体   繁体   中英

Reacts useEffects exhaustive deps only trigger to create component will unmount functionality

I am trying to implement a useEffect callback to dispatch an action before unmounting a component. The point of this action is to store the last state of my component so I can resume from that state the next time this component is loaded. I only want this callback to be triggered on unmount.

When trying to use an empty dependency array for my useEffect, the 'exhaustive-deps' rule in reacts recommended 'eslint-plugin-react-hooks' demands I include the value I am trying to persist. This results in the effect and therefore action being triggered every time I store state.

Is there a better way to handle this situation then disabling eslint for this line?

Here is what I want:

...
const [value, setValue] = useState('');

useEffect(() => {
    return () => {
        storeValueAction(value);
    };
}, []);
...

The way eslint-plugin-react-hooks wants it and results in the action being dispatched on every state change:

...
const [value, setValue] = useState('');

useEffect(() => {
    return () => {
        storeValueAction(value);
    };
}, [value, storeValueAction]);
...

Is there something other than useEffect I should be using for this?

Even if you implement it in the current manner and disable the eslint rule, the expected result won't be correct since the state value dispatched on unmount will be the state value during the initial mount due to closure.

For such a case, you can make use of useRef along with useEffect to achieve a desired result. Once you do that you can safely disable the eslint rule being assured that you code won't result in an unexpected behaviour

const [value, setValue] = useState('');
const valueRef = useRef(value);

useEffect(() => {
   valueRef.current = value;
}, [value]);

useEffect(() => {
    return () => {
        storeValueAction(valueRef.current);
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
}, []);

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