fireship-io / fireship.io

Build and ship your app faster https://fireship.io
3.58k stars 1.32k forks source link

courses/react/basics-state/ #792

Open utterances-bot opened 2 years ago

utterances-bot commented 2 years ago

State

Working with the useState hook

https://fireship.io/courses/react/basics-state/

Ever-It-Lazy commented 2 years ago

I don't understand what's going on here?

  const handleClick = () => {
    setCount((prev) => {
      setPrevCount(prev);
      setCount(count + 1);
    });
  };
  1. handleClick() is an event handler function
  2. it calls setCount(), which creates a function with the argument prev
    1. But where does prev get passed in? Is it the implicit event from handleClick()?
  3. setPrevCount() sets the prevCount to prev...except I still don't know what prev is
  4. then another setCount() runs, that sets count to count + 1
  5. so now the outer setCount() (that got passed a function) sets count to...I don't know what?
Sumit70421 commented 2 years ago

@Ever-It-Lazy the prev is implicit parameter in setCount() which keeps track of previous value. Every setFunction in useState hook has it as a parameter. In this context we want to update prevCount variable to current count, as we have to update the current count to +1.