mdakovac
mdakovac

Reputation: 61

Redux state variable undefined in useEffect return function

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?

Upvotes: 1

Views: 1219

Answers (1)

buzatto
buzatto

Reputation: 10382

you can anchor your value using useRef to have access to its value on cleanup function. You get undefined because of closure, where your function saves the reference value once is declared:

const ExampleComponent = () => {
  const dispatch = useDispatch();

  const stateVariable = useSelector(state => state.variable);
  const stateRef = useRef();
  stateRef.current = stateVariable;
  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(stateRef.current);
      }
  }, []); // leave empty so it runs only on mount/unmount

  return null;
}

Upvotes: 2

Related Questions