Basic Usage of Redux Toolkit

Home / Blog / Technology / Basic Usage of Redux Toolkit

10/22/2020

Basic Usage of Redux Toolkit

Using Redux was a nightmare.

If you have been developing in React Native framework for a while, you had to come across state management library called Redux. The thing is, Redux on its own is a great idea and great concept of state management. However, all the boilerplate code what was before used to create simple Redux Store was just a nightmare.

Redux Toolkit for rescue

As the official page says, Redux Toolkit is "The official, opinionated, batteries-included toolset for efficient Redux development". Long story short - it just makes development your apps using Redux way more easy.

Out of the box you have some features (like selectors or thunks) that were supposed to be added externally to legacy Redux projects.

Vanilia vs ToolKit

Let's have a look at official example of Redux "Vanilia" Example:

const INCREMENT = 'INCREMENT'
const DECREMENT = 'DECREMENT'
function increment() {
  return { type: INCREMENT }
}
function decrement() {
  return { type: DECREMENT }
}
function counter(state = 0, action) {
  switch (action.type) {
    case INCREMENT:
      return state + 1
    case DECREMENT:
      return state - 1
    default:
      return state
  }
}
const store = Redux.createStore(counter)

And, let the magic happen, the Redux Toolkit's implementation:

const counterSlice = createSlice({
  name: 'counter',
  initialState: 0,
  reducers: {
    increment: state => state + 1,
    decrement: state => state - 1
  }
})
const store = configureStore({
  reducer: counterSlice.reducer
})
const { actions, reducer } = counterSlice
const { increment, decrement } = actions

As you can see, out of the box we have much less boilerplate code to use simple counter reducer.

createSlice functon allows us to provide an object with the reducer functions, and it will automatically generate the action type strings and action creator functions based on the names of the reducers we listed.

createSlice returns a "slice" object that contains the generated reducer function as a field named reducer, and the generated action creators inside an object called actions.

Keep in mind, that in production-ready code, the thinks in vanilia code would be also splitted. Different files (with single-responsibility principle in mind) for actions, types, and reducers would generate 3 files for a very simple counter.

When we use createSlice we can combine all the Redux's goods with simplicity of use.

Let's use this counter

Let's create a very simple component which will use redux-toolkit

Setup Dependencies

First of all, we need to setup all the dependencies for our project. Let's start with installing redux, redux-toolkit and react-redux.

We can easily do that by typing in: yarn add @reduxjs/toolkit redux react-redux

Our component

Here is the code snippet of basic React Native component:

export default function Example() {
  const onIncrement = () => {
    //...
  };
  const onDecrement = () => {
    //...
  };
  return (
    <View style={styles.container}>
      <Text>Counter Redux Toolkit Example</Text>
      <View style={styles.row}>
        <Button onPress={onDecrement} title="-" />
        <Text>{0}</Text>
        <Button onPress={onIncrement} title="+" />
      </View>
      <StatusBar style="auto" />
    </View>
  );
}

Using useSelector

First of, we create a selector function which in this case, will return our state. In more complex scenarios, selector function can basically select desired value (e.g. get all todos with state 'completed' or something similar).

We do it like so:

export const counterSelector = state => state;

Then in our Example view, we get the state via selector using:

import { useSelector } from "react-redux";
...
export default function Example() {
  const counter = useSelector(counterSelector);
...
<View style={styles.row}>
  <Button onPress={onDecrement} title="-" />
  <Text>{0}</Text>
  <Button onPress={onIncrement} title="+" />
</View>
...

Using useDispatch

Now, we want to bind our actions to the buttons. We can do that by using useDispatch function.

First of all, we add our dispatch to Example component:

import { useDispatch, useSelector } from "react-redux";
...
export default function Example() {
  const counter = useSelector(counterSelector);
  const dispatch = useDispatch();
...

Then, we bind our actions to our buttons via onIncrement and onDecrement functions like so:

import { counterSelector, decrement, increment } from "../store/counterSlice";
...
  const onIncrement = () => {
    dispatch(increment());
  };
  const onDecrement = () => {
    dispatch(decrement());
  };

And voila!

Final Result

You can get all the example code on our Github, have a look there.

Summary

As you can see, Redux-Toolkit is a very staright-forward way of using Redux in our React Native apps. We will continue our mini Redux-Toolkit series with more topics related to RTK, so stay tuned!

Author

Szymon Nowak

CEO

?

Not sure what tech to choose?

Reach out to aur executive consultants for personalized guidance on how best to approach your project