Learning the React Framework - 003 Component State and Side Effect Updates
State Abstraction
In actual development scenarios, frontend receives a lot of data, whether it's initial default data for the page or API data passed from the backend. We need a method to save this data, and state is a function implemented by React.
According to the description in React's basic concept theory, UI is influenced by State to change into different forms. We hope each UI can preserve its own state and unidirectionally update state through functions we design.
useState
Components in React are just function encapsulations. When a function is executed, its memory reference gets cleared. We want state to persist in our components according to page logic usage. React implemented a hook (which can be viewed as an official utility function) called useState that allows state to persist.
From the example, we can observe that we call useState in the component and set an initial value, change state according to our defined method, and after state changes, the page rerenders and we find the state has been updated.
How useState Works Internally
Simply put, useState does two things for us:
- Allows state values that would otherwise not persist after rerender to continue existing.
- Triggers rerender again after state updates.
useState is an encapsulated closure space, which is the implementation of state abstraction.
Each time we call useState, we receive the state and the side effect function that triggers it from the function, then update the page. This abstraction is just a very simple description. The actual implementation is much more complex, involving initial value observation, node slicing, etc... Really quite interesting 😇😇
State Management for Arrays and Objects
In React state management, any type of data must be treated as immutable. You should not directly change objects under React state. Instead, when you want to update an object (or array), you need to create a new object (or copy an existing object), then set state to use that copy.
When managing object data with state, we can use destructuring to modify state, Example
For array data state management, just like objects, we shouldn't directly change values in the array, but need to create or return new objects.
Additionally, when changing complex object types, be careful about whether you're changing shared memory references, otherwise unexpected errors can easily occur.
Resetting State with Key
Key is an attribute that identifies nodes, commonly used when rendering lists, allowing React to identify the uniqueness of nodes. But when managing state, you can also use Key to reset state. This mainly utilizes the characteristic that when key values change, rerendering occurs.
References
If you want to understand why state is immutable, you can go here