I’ve been digging deeper into React as I prepare to start my new job at Nebula.tv next week.
One of the things I’ve been trying to understand is how exactly React knows that the useState()
method (and associated state) is tied to it’s specific component and not any other component on the page.
function Counter() {
const [count, setCount] = React.useState(0);
return (
<button onClick={() => setCount(count + 1)}>
Value: {count}
</button>
);
}
For example, how does the setCount()
method trigger a render on the <Counter />
component its used it, and not any other one on the page?
When I asked this question on social media, I got back so many responses that explained what React does: associates the state with the component and listens for changes.
No one could tell me how it actually does that. And when I pushed more for that information, pretty much every gave me a hand-wavy “React handles that internally for you” answer.
I appreciate when tools make hard stuff easier for you. But I also like to understand how exactly they do that.
And sometimes, it feels like a lot of developers just don’t care how their code works, as long as it does.
🎉 New Year Sale! Now through the New Year, get 40% off your first year of Lean Web Club membership. Level-up as a developer. Click here to learn more.