Search code examples
reactjsuse-effectuse-stateuse-ref

React useState hook always comes as undefined when setting it in useEffect


In my React application, I have a useEffect that checks if an element has the display style none set to it. If it does then it should set the state to false, however it always comes back as undefined.

const [testingProp, setTestingProp] = useState();

useEffect(() => {
    const styles = getComputedStyle(customerPropertyTypeSection.current);

    if (styles.display == 'none') {
      setTestingProp(false);
      console.log('style set to none'); // this prints
      console.log(testingProp); // this prints 'undefined'
    }
  }, []);

Solution

  • setState in React acts like an async function.
    So putting a console.log(state) right after setting it, will most likely show the former value, which is undefined in this case, as it doesn't actually finish updating the state until the log command runs.

    You can use a deticated useEffect hook with the relevant state as a dependency to act upon a change in the state.

    Example:

    useEffect(() => {
       console.log(state);
    }, [state]);
    

    Basically, the callback function in the example will run every time the state changes.


    P.S. - maybe you can do without the useEffect you are using here to populate the state.
    If you have access to customerPropertyTypeSection.current initially, you can do something like this:

    const [testingProp, setTestingProp] = useState(() => {
       const styles = getComputedStyle(customerPropertyTypeSection.current);
       return styles.display !== 'none';
    });
    

    If the example above works for you, then the useEffect you are using is redundant and can be removed.