Skip to content

Instantly share code, notes, and snippets.

@hemepositive
Created December 10, 2020 20:46
Show Gist options
  • Save hemepositive/81d88645a00c7aa1a9f54f013e5d3f1b to your computer and use it in GitHub Desktop.
Save hemepositive/81d88645a00c7aa1a9f54f013e5d3f1b to your computer and use it in GitHub Desktop.
Reducer Pattern useReducer React Notes
const [state, dispatch] = useReducer(reducer, initialState);
------------------------------------------------------------------------------------------------
DEFINITIONS:
Reducers ->
- Reducers are functions that take input and decide what to do it with it in one central spot.
- Reducers return one thing => state
- Redux Reducers™️ are a specific usage of reducers that interpret events in your application, and how that changes application state.
Actions -> Actions are objects that describe an event
Dispatch -> Function that sends or "dispatches" an action to a reducer
------------------------------------------------------------------------------------------------
HOW TO USE:
To get it working, we need to do a few things: (from css-tricks)
1. Define an initial state.
2. Provide a function that contains actions that update the state. (onClick handlers dispatch actions to reducer)
3. Trigger useReducer to dispatch an updated state that’s calculated relative to the initial state.
Ken Dodd says:
Using a State Reducer with Hooks
Ok, so the concept goes like this:
1. End user does an action
2. Dev calls dispatch
3. Hook determines the necessary changes
4. Hook calls dev's code for further changes 👈 this is the inversion of control part
5. Hook makes the state changes
LINKS:
*https://www.freecodecamp.org/news/how-to-understand-reducers-you-can-use-them-without-redux/
https://css-tricks.com/getting-to-know-the-usereducer-react-hook/
https://www.robinwieruch.de/react-usereducer-hook
https://kentcdodds.com/blog/the-state-reducer-pattern-with-react-hooks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment