This was originally posted as a twitter thread: https://twitter.com/chrisachard/status/1179015849459507200
Does Redux have you confused?
It can be simpler with the new Redux hooks.
🔥Here's a crash course into Redux, and how you can use it with React function components:
It's most often used with React (via react-redux)
This lets you access or change your state from ANY component in your tree
Your state lives in a central Redux store
That store is created with a function called a reducer
A reducer takes in a state and an action,
and returns the same or a NEW state
The store is given to your app using the
Provider from react-redux
Use the provider to wrap your entire app, so that any component in your app can access the store
To get data out of the store, use the
useSelector hook from react-redux
selector is just a fancy word for: "function that gets data from the store"
useSelector takes a callback, which gets the entire redux state, and you just pick out what you need for that component
All actions should have a 'type' key
They may also have additional keys (parameters)
Actions are not "called", but are "dispatched" to the reducers
type is what tells the reducer what to do (return a new state or the old one)
To change data in the store, first write your reducer:
Reducers are often written with switch/case statements, but don't have to be
They just have to take in an action and a state, and return a new state
It's important that reducers return a NEW state object (and not mutate the old one) so that your components will re-render when something changes
Don't set state values in reducers - only ever return a new state object with changed values
To dispatch an action, use the
useDispatch hook from react-redux
call useDispatch with an action object,
which will run through the reducers,
and will potentially change the state
All connected components (that call useSelector) will automatically get the new state
This is treated like props or state changing - useSelector will automatically detect changes and React will re-render the component
Redux can be used in much more complex ways, but the core is always:
- dispatch an action to the store
- which may or may not change the state via reducers
- access that state with a selector
- and changes will automatically re-render your app
View and play around with the code used in this course on codesandbox:
Like this crash course?
Thanks for reading!