Created
August 27, 2019 15:58
-
-
Save djD-REK/ae67a62bad5d58a05a9ec7f0fe294946 to your computer and use it in GitHub Desktop.
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
// Lifting State Up (React.js Example) by Dr. Derek Austin 🥳 | |
// Adapted from code by Kent C. Dodds and the React docs | |
// https://kentcdodds.com/blog/application-state-management-with-react | |
// https://reactjs.org/docs/lifting-state-up.html | |
import React from "react"; | |
import ReactDOM from "react-dom"; | |
import "./styles.css"; | |
function CounterDisplay({ count }) { | |
// We pass the mutable state to the counter display function | |
return <h2>The current counter count is {count}</h2>; | |
} | |
function CounterButton({ count, incrementOnClick }) { | |
// We pass the mutable state and increment function from the app to the button function | |
return <button onClick={incrementOnClick}>{count}</button>; | |
} | |
function Counter() { | |
// We lift state up one level, from the component to the app | |
const [count, setCount] = React.useState(0); | |
const incrementCounter = () => setCount(current => current + 1); | |
return ( | |
<div> | |
<CounterDisplay count={count} /> | |
<CounterButton count={count} incrementOnClick={incrementCounter} /> | |
<h3>State is lifted from component to app level</h3> | |
</div> | |
); | |
} | |
const rootElement = document.getElementById("root"); | |
ReactDOM.render(<Counter />, rootElement); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment