Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/mununki/practice-react-hooks
A tiny example of the React Hooks - How to replace the React Redux
https://github.com/mununki/practice-react-hooks
Last synced: 3 days ago
JSON representation
A tiny example of the React Hooks - How to replace the React Redux
- Host: GitHub
- URL: https://github.com/mununki/practice-react-hooks
- Owner: mununki
- Created: 2019-02-07T06:13:48.000Z (almost 6 years ago)
- Default Branch: master
- Last Pushed: 2022-12-10T00:37:11.000Z (about 2 years ago)
- Last Synced: 2024-04-24T03:22:04.972Z (8 months ago)
- Language: JavaScript
- Homepage:
- Size: 937 KB
- Stars: 3
- Watchers: 0
- Forks: 0
- Open Issues: 20
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# Practice of the React Hooks - How to replace the React Redux
This is a tiny example using the React Hooks working like React Redux.
1. `useHoodux()` = `useState()` + `useContext()`
2. `useReducer()`## How to replace the Redux with React Hooks
### Create the store (initValue + reducer)
```javascript
// App.jsconst initValue = {
isLogin: false,
token: ""
};const reducer = (state, action) => {
switch (action.type) {
case "setLogin":
return { isLogin: action.payload };
case "setToken":
return { token: action.payload };
default:
throw new Error("wrong action.type");
}
};
```### Wrap the top level component(eg. App.js) with Context
```javascript
// App.jsconst MyContext = React.createContext();
const App = () => {
const [state, dispatch] = useReducer(reducer, initValue);return (
);
};
```> You can use the context wrapper component in higher order if you like.
### Pull and use `state` and `dispatch`
```javascript
// Login.jsconst { state, dispatch } = useContext(MyContext);
const handleLogin = () => {
dispatch({ type: "setLogin", payload: true });
};return
{state.isLogin ? "You are logged in" : "Not logged in"};
```## Conclusion
`useReducer` make a lot easier to pull and use the `state` and `dispatch` instead of using `connect()` in React Redux. If you're familiar with it, you know how it works. In React Redux,every single component, you want to use `state` or `dispatch`, needs to be connected. But with `useReducer`, you need to call it just once in component if you want it to be.