Skip to content

Instantly share code, notes, and snippets.

@SyunWatanabe
Created June 10, 2021 16:30
Show Gist options
  • Select an option

  • Save SyunWatanabe/b60d5a8cc0fdb065c7417f117f0d78c3 to your computer and use it in GitHub Desktop.

Select an option

Save SyunWatanabe/b60d5a8cc0fdb065c7417f117f0d78c3 to your computer and use it in GitHub Desktop.
// 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