DEV Community

Discussion on: Accessing React State right after setting it

Collapse
 
dance2die profile image
Sung M. Kim • Edited

Welcome to DEV André 👋.

You're welcome & thank you for taking time for the reply, as it means much to me :)

As aside note, using hooks, a similar way is to accomplish is to use useEffect (as you do for componentDidUpdate).

e.g.)

function App() {
  const [name, setName] = useState(undefined);

  useEffect(() => {
    const fetchName = async () => {
      const remoteName = await (await fetch("...")).json();
      // remoteName => 'André'
      setName(remoteName);
    };

    fetchName();

    // At this point, name is still "undefined", not "André"
    console.log(name);
  }, []);

  useEffect(() => {
    // You can skip your process, when the name is not yet set.
    if (name === undefined) return;

    // At this point, the name is "André"
    console.log(name);
  }, [name]);

  // return ...
}

Enter fullscreen mode Exit fullscreen mode