Simple React Native Redux counter example
If you are learning React Native and Redux and still really don’t understand Redux try looking at this simple counter app that I made. This app aims to clearly illustrate the key concepts of Redux (store, actions, reducers) in a very small toy project.
This is what it looks like:
The code can be found here.
Main idea to keep in the back of your head:
- Instead of storing the data inside of our components we basically extract the data to an external store (our
store
) - We then communicate with this store through an “API” which is the Redux language, or in our case the
react-redux
library - The only way you can change the store is by dispatching an action to your reducer
- Your reducer then decides how to change the state, depending on the action you gave it (ex. increment counter)
Key concepts:
- Store: Your store is a plain JS object that is read-only. The only way to change the store is through reducers.
- Actions: Actions are JS objects that have a
type
field, nothing more, nothing less. - Reducers: Reducers are functions that take in the state and an action and return back the new state. A reducer must be a pure function, that is, it shouldn’t have any side effects. In essence a reducer can be formulated like this
(state, action) => state
This is what I learned:
- Use
useSelector
to grab values from the store - Use
useDispatch
to dispatch actions to your reducer - A Redux app only really has one reducer, the
RootReducer
- Wrap your whole app in a single component so you can wrap that in a
Provider
component to give access to the store - When importing your Action Creators make sure to import them like this
{ addTodo }
Comments