skip to Main Content
import React, { useState } from 'react';

export default function Counter() {
  const [count, setCount] = useState(0);

  const handleClick = () => {
    setCount((prevCount) =>  prevCount + 1);
  };

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick = {handleClick}>
        Click me
      </button>
    </div>
  );
}

I am new to React and just trying to grasp exactly how it works. Where does prevCount come from, is this callback needed?

2

Answers


  1. Here’s a breakdown of how it works:

    • Initialize a variable:
    const [count, setCount] = useState(0);
    

    count is getter that allows you to access the current value & setCount is setter function that allows you to update the value.
    While useState(0) represents the initial value of count.

    • Manage handler:
    const handleClick = () => {
        setCount((prevCount) =>  prevCount + 1);
    };
    

    Here, prevCount is a variable that holds the current value of count.
    You can name it whatever you like.
    Work: On button click, setCount() increase with 1 because the prevCount act as current value & prevCount + 1 means add 1 in current value.

    Login or Signup to reply.
  2. From documentation:

    If you pass a function as nextState, it will be treated as an updater function. It must be pure, should take the pending state as its only argument, and should return the next state. React will put your updater function in a queue and re-render your component. During the next render, React will calculate the next state by applying all of the queued updaters to the previous state

    Example:

    const [count, setCount] = useState(0);
    
    function handleClick() {
      setCount(a => a + 1); // setCount(0 => 1)
      setCount(a => a + 1); // setCount(1 => 2)
      setCount(a => a + 1); // setCount(2 => 3)
    }
    
    

    Link

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search