Search code examples
javascriptreactjscomponentsstate

How to access the latest state value in the functional component in React


import React, { useState } from "react";
import Child from "./Child";
import "./styles.css";

export default function App() {
  let [state, setState] = useState({
    value: ""
  });

  let handleChange = input => {
    setState(prevValue => {
      return { value: input };
    });
    console.log(state.value);
  };
  return (
    <div className="App">
      <h1>{state.value}</h1>

      <Child handleChange={handleChange} value={state.value} />
    </div>
  );
}
import React from "react";

function Child(props) {
  return (
    <input
      type="text"
      placeholder="type..."
      onChange={e => {
        let newValue = e.target.value;
        props.handleChange(newValue);
      }}
      value={props.value}
    />
  );
}

export default Child;

Here I am passing the data from the input field to the parent component. However, while displaying it on the page with the h1 tag, I am able to see the latest state. But while using console.log() the output is the previous state. How do I solve this in the functional React component?


Solution

  • React state updates are asynchronous, i.e. queued up for the next render, so the log is displaying the state value from the current render cycle. You can use an effect to log the value when it updates. This way you log the same state.value as is being rendered, in the same render cycle.

    export default function App() {
      const [state, setState] = useState({
        value: ""
      });
    
      useEffect(() => {
        console.log(state.value);
      }, [state.value]);
    
      let handleChange = input => {
        setState(prevValue => {
          return { value: input };
        });
      };
    
      return (
        <div className="App">
          <h1>{state.value}</h1>
    
          <Child handleChange={handleChange} value={state.value} />
        </div>
      );
    }