Bruce
Bruce

Reputation: 83

LifeCycle of onChange in react

I am writing a simple react application, now I am working on an element that can take the user's input. I have been very curious about the order of the execution of line of code inside the onChange() function. So I added a little print statement to see how exactly things are changed.

Here's my code

function CreateReview() {

    
    const [input, setInput] = useState({
    title:'',
    content:''
})

useEffect(() => {
    console.log('render');
 },[input])

function handleChange(event){
    const {name, value} =event.target;

    console.log(1)
    setInput(prevInput=>
        {
            console.log(2)
            return{
                 ...prevInput, //...prevInput is to reserve the last Input
                 [name]: value //name is dynamic, "title" then setTitle, "content" then setContent.
                
            }
        }
    )
    console.log(3)
    console.log(event.target);
}

function handleClick(event){
    event.preventDefault();
    console.log(input);
}

return <div className = "container">
    <h1>Create Review</h1>
    <form>
        <div className="form-group">
            <input onChange={handleChange} name="title" value={input.title} autoComplete="off" className = 'form-control' placeholder="Your Name"></input>
        </div>

        <div className="form-group">
            <textarea onChange={handleChange} name="content" value={input.content} autoComplete="off" className = 'form-control' placeholder="Review Content"></textarea>
        </div>
        
        <button onClick={handleClick} className="btn btn-large btn-info">Add Note</button>
    </form>
</div>
}


export default CreateReview;

And here's the output console

Console screenshot

I wonder why it goes 1,3,2. is there any reason behind it?

Upvotes: 0

Views: 258

Answers (1)

Kushal Jain
Kushal Jain

Reputation: 3186

Kindly go to react document to read more about how state works in react.

As far as your concerned useState or setState are the async events, so whenever you are try to call them it will execute later rather do synchronously(line by line).

Upvotes: 1

Related Questions