Last active
July 16, 2021 21:52
-
-
Save Tripple-A/f9b2a598f4bc9801caefbfb070171b61 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
import { useReducer } from "react"; | |
const initialState = { | |
age: 0, | |
height: 0, | |
hobby: "None", | |
}; | |
const reducer = (state, action) => { | |
switch (action.type) { | |
case "startBabyStage": | |
return { ...state, age: 1, height: 29, hobby: "Biting" }; | |
case "startTeenStage": | |
return { ...state, age: 13, height: 61, hobby: "Gaming" }; | |
case "startAdultStage": | |
return { ...state, age: 20, height: 69, hobby: "Coding" }; | |
case "restart": | |
return initialState; | |
default: | |
throw new Error(`No such type: ${action.type}`); | |
} | |
}; | |
function App() { | |
const [state, dispatch] = useReducer(reducer, initialState); | |
const { age, hobby, height } = state; | |
return ( | |
<div className="App"> | |
{console.log("rerendered")} | |
<div> | |
<h3>Age: {age}</h3> | |
<h3>Height: {height} inches</h3> | |
<h3>Hobby: {hobby}</h3> | |
</div> | |
<button onClick={() => dispatch({ type: "startBabyStage" })}>Baby</button> | |
<button onClick={() => dispatch({ type: "startTeenStage" })}> | |
Teenager | |
</button> | |
<button onClick={() => dispatch({ type: "startAdultStage" })}> | |
Adult | |
</button> | |
<button onClick={() => dispatch({ type: "restart" })}>Restart</button> | |
</div> | |
); | |
} | |
export default App; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment