useState hook

DEMO
0
Console
Every time a state changes, the component in which the state is located, as well as all its children components are re-rendered.
UseStateDemo.jsx

function Counter() {
  const [count, setCount] = React.useState(0);  
  console.log(`New count: ${count}`)

  const decrementCount = () => {
    if (count > 0) setCount(count => count - 1);
  };

  return (
    <>
      <MinusBtn onClick={decrementCount} />
      <div>{count}</div>
      <PlusBtn onClick={() => {
          setCount(count => count + 1);
        }}
      />
    </>
  );
};

export default Counter;
State is immutable. It shouldn't be modified directly. Always use the setter function to modify the state.
If you need the previous value to update the state, you should pass a function that receives the previous value and returns the new value.

Note: Code snippets do not include styling details unless they are the focus of the exercise.

Copyright © 2022 Explore React