- Introduction Now that we’ve learned about State in React components, it’s time to understand how to manage State effectively. Geek and Gal will guide us through this essential concept in React development.
- Keeping State Close to the Root
- Lifting State Up
class ParentComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
sharedValue: ''
};
}
render() {
return (
<div>
<ComponentA sharedValue={this.state.sharedValue} />
<ComponentB sharedValue={this.state.sharedValue} />
</div>
);
}
}
- Hilarious Example
import React, { useState } from 'react';
function MoodChanger() {
const [friendAMood, setFriendAMood] = useState('😀');
const [friendBMood, setFriendBMood] = useState('😀');
return (
<div>
<h2>Friend A's mood: {friendAMood}</h2>
<button onClick={() => setFriendAMood('😂')}>Make Friend A Laugh</button>
<h2>Friend B's mood: {friendBMood}</h2>
<button onClick={() => setFriendBMood('😍')}>Make Friend B Love</button>
</div>
);
}
[[conversation]] geek_happy: ‘Haha, that’s a fun example! We’re using State effectively to manage the moods of two friends in our Mood Changer app!’ gal_happy: ‘I’m glad you like it! Keep practicing and create more engaging apps with proper state management!’ [[