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

Viewed 11956
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?

3 Answers

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>
  );
}

Two solution for you: - use input value in the handleChange function

let handleChange = input => {
   setState(prevValue => {
     return { value: input };
   });
   console.log(state.value);
 };
  • use a useEffect on the state

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

Maybe it is helpful for others I found this way...

I want all updated projects in my state as soon as I added them so that I use use effect hook like this.

useEffect(() => {
    [temp_variable] = projects //projects get from useSelector
    let newFormValues = {...data}; //data from useState
    newFormValues.Projects = pro; //update my data object
    setData(newFormValues); //set data using useState
},[projects]) 
Related