CodeBlanks Logo Icon CodeBlanks

Summary - State management

Combine createSlice, useDispatch and useSelector to write a counter.

Summary - State management

In this group you learned Redux, Redux Toolkit, createSlice, useDispatch and useSelector. configureStore creates the store; createSlice produces reducers and action creators. useDispatch sends actions; useSelector reads state.

Now we will combine them into a working counter. First the slice is defined, then the store is set up, finally a component increments via dispatch and shows the value with useSelector. This pattern is the skeleton of every Redux app.

Practice Summary - Counter slice

Define counterSlice. With createSlice set name: 'counter', initialState: { value: 0 }, reducers: { increment, decrement }. Export the reducer with export default and the actions with export const.

Starter code

App.js
import { createSlice } from '@reduxjs/toolkit';

// define counterSlice

Sample solution

App.js
import { createSlice } from '@reduxjs/toolkit';

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

export default counterSlice.reducer;
export const { increment, decrement } = counterSlice.actions;

Practice Summary - Counter component

Complete the Counter component. Read the value with useSelector((state) => state.counter.value). Call dispatch(increment()) via useDispatch. Return <Text>{count}</Text> and an increment button.

Starter code

App.js
import React from 'react';
import { Button, Text, View } from 'react-native';

export function Counter() {
  // get count and dispatch; return Text and Button

  return null;
}

Sample solution

App.js
import React from 'react';
import { Button, Text, View } from 'react-native';
import { useSelector, useDispatch } from 'react-redux';
import { increment } from './counterSlice';

export function Counter() {
  const count = useSelector((state) => state.counter.value);
  const dispatch = useDispatch();

  return (
    <View>
      <Text>{count}</Text>
      <Button title="Increase" onPress={() => dispatch(increment())} />
    </View>
  );
}

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match the flow parts

Term Meaning
createSlice Produces the slice
configureStore Sets up the store
useDispatch Sends an action
useSelector Reads state

2 Write the slice name value

Question
const counterSlice = createSlice({
  name: '____',
  initialState: { value: 0 },
  reducers: {}
});
Answer
const counterSlice = createSlice({
  name: 'counter',
  initialState: { value: 0 },
  reducers: {}
});

Explanation: counter is the slice name.

All lessons in Advanced