Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

168
Views
Status tracking and props in hooks - How does React keeps (track) state and props in Hooks?

I know that in React class components React uses the "this" binding to "track" props and state. In hooks it is achieved thanks to closures, is my doubt?

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

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

This code works as you would expect a counter, if you were using class component you would have to use setState() in callback mode to access the previous state, but in hooks how does the magic happen?

are there any bindings on the hooks or not?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

React keeps track of state by internally counting the number of times useState is called the first time a component mounts. The value passed into useState is then set into React's internal state. For example, given

const Component = () => {
  const [state1, setState1] = useState('one');
  const [state2, setState2] = useState('two');
  return 'foo';
};

React will then have the following state stored internally:

['one', 'two']

with one item in the (hidden, internal) state array for each call of useState that there is.

When a state setter is called, the corresponding item in the internal state array will be updated, and then the component will re-render. When a component re-renders, each useState call then returns the appropriate item in the internal state array. The first useState call will return the first item in the internal state array, the second useState call will return the second item, and so on.

In your code, with hooks, the click handler has a closure over the value of count that existed at that particular render of Counter.

if you were using class component you would have to use setState() in callback mode to access the previous state

Not really - if this code was a class component, it would be free to reference this.state.count directly without using the callback version.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!