How exactly state work in React?
And let's start with a fundamental React principle that we already know. So remember how we learned that in React, we do not manipulate the DOM directly when we want to update a component's view, right? So React is declarative, not imperative, so we never touch the DOM in our code. But if that's the case, then this leads us to the question of how we update the component on the screen whenever some data changes or whenever we need to respond to some event like a click.
Now, we already know that the answer to this question is state, but here we are trying to derive it from first principles.
So anyway, to answer that question, we need to understand another fundamental React principle, which is the fact that React updates a component view by re-rendering that entire component whenever the underlying data changes. But for now, know that re-rendering basically means that React calls the component function again, so each time the component is rendered. So conceptually, we can imagine this as React removing the entire view and replacing it with a new one each time a re-render needs to happen.
Now, React preserves the component state throughout re-renders, and so even though a component can be rendered and re-rendered time and time again, the state will not be reset unless the component disappears from the UI entirely, which is what we call unmounting. Now speaking of state, it is when state is updated that a component is automatically re-rendered.
So let's imagine that there is an event handler in the view, for example, on a button that the user can click. So the moment that button is clicked, we can update a piece of state in our component using the set function coming from the useState hook. Then when React sees that the state has been changed, it'll automatically re-render the component, resulting in an updated view for this component.
And with this, I hope that the mechanics of state in React are now really clear to you. So the conclusion of all this is that as React developers, whenever we want to update a component view, we update its state.
And so React will then react to that update and do its thing. And in fact, this whole mechanism is so fundamental to React that it's actually the reason why React is called React in the first place. So on a high level, moving from the component level to the application level now, React reacts to state changes by re-rendering the user interface. That's the main thing that it does. And therefore, it was decided to call this library React.