Skip to content Skip to sidebar Skip to footer

Onchange Is One Character On Delay - Hooks

I am new to React and Hooks. I create a simple search bar where the user can type some text. However, if I console.log the state after the onChange, it is always one character behi

Solution 1:

As you know, useState is async function. When you use useState inside functional Component, you have to handle variable in useEffect to see change of variable like this:

const App = () => {
  const [search, setSearch] = useState("");
  const onChange = e => {
    e.persist();
    setSearch(e.target.value);
  };

  useEffect(() => {
    console.log("Search message inside useEffect: ", search);
  }, [search]);

  return <input onChange={onChange} />;
};

Post a Comment for "Onchange Is One Character On Delay - Hooks"