https://github.com/ebazhanov/i-love-userreducer
Several examples of how to `useReducer`
https://github.com/ebazhanov/i-love-userreducer
examples react usereducer-hooks
Last synced: about 1 month ago
JSON representation
Several examples of how to `useReducer`
- Host: GitHub
- URL: https://github.com/ebazhanov/i-love-userreducer
- Owner: Ebazhanov
- Created: 2020-06-17T18:08:19.000Z (almost 6 years ago)
- Default Branch: master
- Last Pushed: 2020-06-17T22:03:03.000Z (almost 6 years ago)
- Last Synced: 2025-03-17T09:52:25.859Z (about 1 year ago)
- Topics: examples, react, usereducer-hooks
- Language: JavaScript
- Homepage: https://reactjs.org/docs/hooks-reference.html#usereducer
- Size: 355 KB
- Stars: 3
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# Find out how to `useReducer` in different cases:
> [useReducer](https://reactjs.org/docs/hooks-reference.html#usereducer) is an alternative to useState. useReducer is usually preferable to useState when you have complex state logic that involves multiple sub-values or when the next state depends on the previous one.
## We will start with `useState` and convert it later to `userReducer`
```javascript
import React, {useState} from "react";
const App = () => {
const [count, setCount] = useState(0);
return (
{count}
{
setCount(count + 1);
}}
>
useState Count
);
}
export default App;
```
## So now the first example how we can convert `useState` to `useReducer`
```javascript
import React, {useReducer} from "react";
function reducer(count) {
return count + 1;
}
const App = () => {
const [reducerCount, dispatch] = useReducer(reducer, 0);
return (
{reducerCount}
{
dispatch();
}}
>
REDUCER COUNT
);
}
export default App;
```
## Third example with more complex example:
```javascript
import React, {useReducer} from "react";
const initialState = {
count: 0
}
function reducer(state, action) {
if (action === "add")
return {
count: state.count + 1
};
return {
count: state.count - 1
}
}
const App = () => {
const [state, dispatch] = useReducer(reducer, initialState);
return (
{state.count}
{
dispatch("add");
}}
>
ADD
{
dispatch();
}}
>
SUBTRACT
);
}
export default App;
```