Home > OS >  How to get updated React state after being set?
How to get updated React state after being set?

Time:10-21

I have a form that has all text elements. How come when I use this change handler function and set the state using the change event listener, it logs what the state was before the change?

const handleChange = event => {
        const { name, value } = event.target

        setSomeState(prevDateInputs => ({
            ...prevStateInputs,
            [name]: value,
        }))
        
        console.log(someState)    // ← this logs the value of the state before it was changed

    }

CodePudding user response:

In the recent react rfcs release you can use 'use' same as javascript async await method. more details can be found in this link https://github.com/reactjs/rfcs/pull/229

CodePudding user response:

Is it essential to use setState? Could useRef work?

import {useRef} from 'react';

const App = () => {
  const inputRef = useRef(null);

  function handleChange() {
    const {name, value} = inputRef.current;
    console.log({[name] : value});
  }

  return (
    <div>
      <input
        onChange={handleChange}
        ref={inputRef}
        type="text"
        id="message"
        name="message"
      />

    </div>
  );
};

export default App;

But assuming your real use case doesn't involve a console.log, it may not matter if setState doesn't update instantly. In the below example We see the new value displayed on the screen near instantly in the h2 tag even if the console.log shows the old value:

import {useState} from 'react';

const App = () => {
  const [message, setMessage] = useState('');
  const [someState, setSomeState] = useState('');

  const handleChange = event => {

    const { name, value } = event.target
    setMessage(value)
    setSomeState({[name]:value})
    console.log('value is:', someState);
  };

  return (
    <div>
      <input
        type="text"
        id="message"
        name="message"
        onChange={handleChange}
        value={message}
      />

      <h2>{JSON.stringify(someState)}</h2>
    </div>
  );
};

export default App;

Some more details here.

  • Related