Creating a Good State Solution
Explore how to create a good state management solution in React functional components. Understand common challenges with local states, unique keys, and component updates. Learn how React uses its fiber architecture and Hook structures to store and manage state efficiently, enabling smoother UI rendering and state persistency.
We'll cover the following...
Challenges in state management
States are quite capable. A component without states is like a function without variables. It would lack capabilities of reasoning. A piece of UI logic relies on states to work upon continuous interactions with users.
We built a custom state in the previous chapter as follows:
let states = {};// Custom function to get the shared state with a specific key and an initial valuefunction _getM2(initialValue, key) {if (states[key] === undefined) {states[key] = initialValue;}return states[key];}// Custom function to set the shared state with a specific key and trigger re-renderingfunction _setM2(value, key) {states[key] = value;ReactDOM.render(<Title />, rootEl);}
Though this approach works, we need to address a few problems before we can seriously consider using it with React. We'll mention these problems one by one as follows.
The location where the states are allocated is the first major problem:
let states = {}
The preceding states variable is allocated as a global variable, but normally we'd first be interested in states specific to a component. In other words, we need to find a place to define local states.
The second problem of using states is the unique key to identify each of them:
const a = _getM2(0, 'comp_a')