Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Input value onChange - React Hooks

I'm trying to collect the value typed in a input box, but when I use onChange I can only get the previous value. For example after I just typed "text" the latest value to be collected would be "tex"

import React, {useState} from 'react';
import './SearchBar.css';

const SearchBar = (props) => {

    const [input, setInput] = useState('');

    const onChange = (e) => {
        setInput(e.currentTarget.value);
        console.log(input);
    }

    let sugestionList = (
        <ul>
            <li>item 1</li>
            <li>item 2</li>
        </ul>
    )



    return(
        <div className="search-bar">
            <input type="text" placeholder={props.placeholder} onChange={onChange}/>
            {sugestionList}
        </div>

    )
}
like image 984
Felipe Souza Avatar asked Mar 12 '26 22:03

Felipe Souza


1 Answers

That's because updating a state is an asynchronous task. To get the latest state you can use useEffect() hook.

useEffect(() => {console.log("input state is", input)}, [input]) //add the state in dependency array and this useEffect will run whenever state changes//
like image 196
Atin Singh Avatar answered Mar 15 '26 15:03

Atin Singh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!