Created
April 2, 2023 16:19
-
-
Save lejonmanen/9f89caf0a451e810cece67aa1c43a128 to your computer and use it in GitHub Desktop.
React: Lifting state up example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useState } from 'react' | |
/* | |
"Lifting state up" is useful when several components need to share state. | |
In this example, both Parent and Child needs to display the value of | |
"clicks". Child needs to update the value as well. We are lifting the | |
state up, out of the child component, into its parent. | |
1. Move the shared state to the common component - the component that | |
contains all of the components that needs to share state. Here, Parent is | |
the common component, because it contains Child. | |
2. Pass the current value to each component that needs it, using props. | |
3. Create functions that modify the state in the common component. Pass | |
those functions to each component that needs to modify the state. | |
*/ | |
const Parent = () => { | |
const [clicks, setClicks] = useState(0) | |
const whenClick = () => setClicks(clicks + 1) | |
return ( | |
<div> | |
<p> Clicks: {clicks} </p> | |
<Child clicks={clicks} whenClick={whenClick} /> | |
</div> | |
) | |
} | |
const Child = ({ clicks, whenClick }) => ( | |
<p> | |
You have clicked me {clicks} times. <br /> | |
<button onClick={whenClick}> Do it </button> | |
</p> | |
) | |
export default Parent |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment