Supporting Multiple States
Explore how to handle multiple independent states within React function components. This lesson guides you through creating and managing separate states using key-value pairs to effectively control multiple UI elements, enabling better state persistence and re-rendering in your React applications.
Sustain multiple states
Let's see whether we can support multiple states instead of one state.
It's great that we can establish a persistent state within a function component. However, we want more states like that. An app normally contains lots of buttons, switches, and actionable items; each requires a persistent state. So, it's a must-have to support multiple states in the same app.
So, say we need two buttons, and each needs to be driven by a state. Let's extend what we have learned from a single state:
const Title = () => {// Initialize counters for Hello and World with initial values retrieved from _getM(0)let countH = _getM(0);let countW = _getM(0);// Define a function to handle the onClick event for the Hello counter buttonconst onClickH = () => {countH = countH + 1;_setM(countH);};// Define a function to handle the onClick event for the World counter buttonconst onClickW = () => {countW = countW + 1;_setM(countW);};// Render the component with two buttons to increment Hello and World countersreturn (<><button onClick={onClickH}>+</button><h1>Hello+{countH}</h1><button onClick={onClickW}>+</button><h1>World+{countW}</h1></>);};
In the code above, we first create two buttons, one with a "Hello" label and one with a "World" label, and each have their separate event handler, onC1ickH and onClickW respectively. Also, we apply _getM and _setM to both of them and install a couple of logs to help the debug, as shown in the following timeline sketch:
|----0--1-2----------------> clickedH|------------3-4----5------> clickedW0----1--2-3--4-5----6------> updatedH0----1--2-3--4-5----6------> updatedW
From the preceding sketch, we clicked the "Hello" button three times and then clicked the "World" ...