0

I understand useState does not update instantly. Some of the tutorial videos on react shows use of callback function as a way to achieve the result for immediate update. I tried that but it doesnt seem working .attaching the sample code

import { useState } from "react";
const testComponent = () => {
    const [userInputs, setUserInputs] = useState({
        age: '',
        comments: ''
    })

    function commentInputHandler(event) {
        setUserInputs((prevState) => {
            return {
                ...prevState,
                comments: event.target.value
            }
        })
        console.log(userInputs.comments)
    }
    render(
        <textarea onChange={commentInputHandler} className="form-control" required ></textarea>
    )
}
  • 1
    First thing I see - components should begin with an uppercase first letter. – Brian Thompson Feb 17 '22 at 18:00
  • State updates are generally batched and asynchronous, so you won't be able to immediately log the results. You could use `useEffect` to monitor the state changes: `useEffect(() => console.log(userInputs.comments), [userInputs.comments]);` – Andy Feb 17 '22 at 18:03
  • @and so what is the use of having the callback function? Does it have any role in updating the state immediately ? – Sreejith Narayanankutty Feb 17 '22 at 18:05
  • Thanks @BrianThompson for noticing it ,it was a sample code and my interest was to know on the state behavior than capital letter :) – Sreejith Narayanankutty Feb 17 '22 at 18:07
  • Inside the `commentInputHandler` callback, if you need the new state immediately, you already have it under `event.target.value`. Otherwise, the state itself will be up-to-date on the next render. – Emile Bergeron Feb 17 '22 at 18:08
  • 2
    My point is that state updates _are not immediate_. All the callback does is pass in the last state, and then update the state with that information, and the new information. It doesn't stop it being async. – Andy Feb 17 '22 at 18:12

0 Answers0