Yogev
Yogev

Reputation: 125

Trying to read a React state gives the initial state rather than the updated one

I have a React function component that listens to a click of a button and changes a state accordingly. I can see that the state indeed changed as reflated in the view. Yet, when trying to read the current state - it still seem to be the initial one:

import React from "react";

export default function App() {
  const [state, setState] = React.useState("Not Changed");
  const [print, setPrint] = React.useState(null);

  const change = () => {
    setState("Changed!!!");
  };

  React.useEffect(() => {
    setPrint(() => {
      return () => {
        console.warn("state > ", state); //=> "state >  Not Changed"
      };
    });
  }, []);

  return (
    <div className="App">
      <div style={{ border: "1px solid black", marginBottom: "30px" }}>
        <button onClick={change}>Change State</button>
        <div>{state}</div>
      </div>
      <button onClick={print}>Print State</button>
    </div>
  );
}

You can also see the code working here: https://codesandbox.io/s/sweet-lalande-x8w6p?file=/src/App.js

In the browser - I see the html updated to "Changed!!!". But in the console, I still see "state > Not Changed" being printed.

I would really appreciate someone helping me picking up on what I am missing here. Thanks!

Upvotes: 0

Views: 227

Answers (1)

BeHappy
BeHappy

Reputation: 3998

pass state to useEffect:

  React.useEffect(() => {
    setPrint(() => {
      return () => {
        console.warn("state > ", state);
      };
    });
  }, [state]);

Upvotes: 1

Related Questions