Created
June 10, 2021 16:30
-
-
Save SyunWatanabe/b60d5a8cc0fdb065c7417f117f0d78c3 to your computer and use it in GitHub Desktop.
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
| // useReducer | |
| // https://ja.reactjs.org/docs/hooks-reference.html#usereducer | |
| // basic | |
| // const [state, dispatch] = useReducer(reducer, initialArg, init); | |
| // reducer type | |
| // (state, action) => newState; | |
| // when it use?? | |
| // you have complex state logic that involves multiple sub-values or when the next state depends on the previous one. | |
| // sample | |
| const initState = { enegy: 0 }; | |
| const reducer = (state, action) => { | |
| switch (action.weather) { | |
| case "sunny": | |
| return { enegy: state.enegy + 1 }; | |
| case "rainy": | |
| return { enegy: state.enegy - 1 }; | |
| case "cloudy": | |
| return { enegy: state.enegy }; | |
| default: | |
| throw new Error(); | |
| } | |
| }; | |
| const weatherFortune = () => { | |
| const [state, dispatch] = useReducer(reducer, itniState); | |
| const weather = ["sunny", "rainy", "cloudy"]; | |
| const randomNum = Math.floor(Math.random() * weather.length); | |
| const randomWeather = weather[randomNum]; | |
| return ( | |
| <> | |
| <button | |
| type="button" | |
| onClick={() => dispatch({ weather: randomWeather })} | |
| > | |
| click☝ | |
| </button> | |
| <div>Its {randomWeather} today!!!</div> | |
| <div>my enegy is still...{state.enegy}</div> | |
| </> | |
| ); | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment