A variable fetched from Redux state by useSelector is undefined in useEffect return function:
const ExampleComponent = () => {
const dispatch = useDispatch();
const stateVariable = useSelector(state => state.variable);
console.log(stateVariable) // undefined on first render, then "whatever"
useEffect(() => {
// set state on component mount using a generic action creator
dispatch(setStateVariable("whatever"));
return () => {
console.log(stateVariable) // undefined on unmount
}
}, []); // leave empty so it runs only on mount/unmount
return null;
}
Why is stateVariable undefined in the cleanup function? How can I use stateVariable in the cleanup function?