Creating a Good State Solution
Learn about challenges and considerations in custom state management for React components.
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 ...