Last active
January 18, 2022 13:19
-
-
Save lejonmanen/1bcd30c6129254c192016a3cb7f4bc29 to your computer and use it in GitHub Desktop.
React: Lifting state up example, with TypeScript
This file contains 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<number>(0) | |
const whenClick = () => setClicks(clicks + 1) | |
return ( | |
<div> | |
<p> Clicks: {clicks} </p> | |
<Child clicks={clicks} whenClick={whenClick} /> | |
</div> | |
) | |
} | |
interface ChildProps { | |
clicks: number; | |
whenClick: () => void; | |
} | |
const Child = ({ clicks, whenClick }: ChildProps) => ( | |
<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