Home > database >  Why i have trouble using the state updater function while using useState hook?
Why i have trouble using the state updater function while using useState hook?

Time:01-16

While using "const [count, setCount] = useState(0)" useState as so i thought the setCount function is a simple function to update the test variable. But it turns i can't work with it unless i use it in the jsx as so <button onClick={() => setCount(count 1)}>

here's what i tried and it shows no result but blank on the display

function App() {
  const [count, setCount] = useState(0);
  setCount(1);
  return (
    <div> {test   1} A simple div </div>
  );
}

i thought it would display "2 A simple div" but nothing displays.

however this code works

const [count, setCount] = useState(0);
return (
  <div>
        <p>You clicked {count} times</p>
        <button onClick={() => setCount(count   1)}>
        Click me
        </button>
  </div>
);

Thanks

CodePudding user response:

when state update react component re-render.

update the state directly inside the component function re-render the component again. when it re-render again state update function is called so it went into an infinite loop so it renders nothing.

CodePudding user response:

changing the state of the variable that way is wrong, better way to handle the state change is to use previous state, like this:

<button onClick={() => setCount((prev) =>prev   1)}>

here we are giving a click handler a previous state of the variable(in this instance 0).

  • Related