Redux React State Management
By: Segun Subair
Tags: JavaScript, React, State Management, Jsx, Redux

Understanding Redux Workflow

If you worked with React in any capacity at all, it’s highly likely you’ve heard of a library called Redux. If you haven’t used it before you might be wondering what it is and how it might be helpful to you. Well lucky for you, this blog post is here to answer that. In addition, we’ll also cover some of the features that make it popular and how it contrasts with some of the built-in state management techniques in React.

What is Redux?

Redux is a state management library that is commonly used with React to keep changes in state within your app more predictable and traceable. State management is a way to facilitate communication and sharing of data across components. It allows us to provide data to individual components without having to pass down state as props. Example of state in react without redux.

const [board, setBoard] = useState(new Array(9).fill(“”))

Why Use Redux

You might be familiar with the context API in React that allows for creating data that can be accessed throughout the component hierarchy without having to pass down data through every component. One of the benefits of using Redux instead of context is because it allows for a much better debugging experience. The redux dev tool has the ability to trace your state updates by storing every action dispatch. This allows for better debugging and tracing errors that might occur in your code. In addition, Redux middleware enables powerful capabilities that the context API does not provide.

Redux Workflow

Redux stores state in the store and the state can be accessed with the useSelector react hook. An image is provided below to show the redux workflow. Before we dive into the example below, it might be helpful to understand the redux workflow.

The UI (user interface) Typically, the first step in the Redux flow is when the UI triggers a state change. An example would be a Reset Button to clear the board in a Tic-Tac-Toe app. The reset button in React has an on-click function when triggered this dispatch an action that is sent to the reducer and updates the state. In this case, resets the board by setting all indexes to null.

Typically, the first step in the Redux flow is when the UI triggers a state change. An example would be a Reset Button to clear the board in a Tic-Tac-Toe app. The reset button in React has an on-click function when triggered this dispatch an action that is sent to the reducer and updates the state. In this case, resets the board by setting all indexes to null. Action is a JavaScript object that has a type property that describes what we want the action to do. In our example using the tic-tac-toe app will dispatch an action to clear/reset the board(‘RESET_BOARD’). An action object can have other fields with additional information about the state change. We put that information in a property usually called payload.

is a JavaScript object that has a type property that describes what we want the action to do. In our example using the tic-tac-toe app will dispatch an action to clear/reset the board(‘RESET_BOARD’). An action object can have other fields with additional information about the state change. We put that information in a property usually called payload. Reducer is a function that receives the current state and the action object that was dispatched. The redux toolkit allows us to write mutating state functions without having to return a new state object, The reducer updates the state and returns the new state object.

is a function that receives the current state and the action object that was dispatched. The redux toolkit allows us to write mutating state functions without having to return a new state object, The reducer updates the state and returns the new state object. Store is where the state lives and there are some critical methods that we can use.

is where the state lives and there are some critical methods that we can use. Dispatch(action) — This method is the only way to update the state. It accepts an action

getState() — Allows us to retrieve the updated state object

subscribe(listener) — Works like event listeners, allowing code to trigger every time a change takes place

Selectors are functions that extract specific pieces of information from the store’s state. We can use a selector rather than getState which returns all store states as an object.

are functions that extract specific pieces of information from the store’s state. We can use a selector rather than getState which returns all store states as an object. State is contained within the store. It is a concept from React. It is an object that represents the dynamic parts of the app.

As an example, I will be using a tic-tac-toe game to better understand the process.

Component initiating change is the user interface component updating the state. From our tic-tac-toe example, this can be the reset button

State Management without Redux

To manage state without redux, you’ll need to create state in a parent component which will need to be passed down to the child components as props. When the application is small this might not raise a red flag but as the app scales, we start passing props to components that don’t require the data being passed directly, but needs to be passed down as a prop to the target component (also known as prop drilling). In the image example above, the state is being passed through every component to get to the sibling component.

const [board, setBoard] = useState(new Array(9).fill(“”)) const [player, setPlayer] = useState(“X”) const [winner, setWinner] =

useState({X:x, O:o, announce:’Player’, gameOver:false})

State Management With Redux

Redux fixes the prop drilling problem by allowing us to pass data without having to pass the props through multiple layers of components. Redux uses a central store that holds the entire state of the application. Each component can access the stored state without having to send down props from one component to another.

import { configureStore } from ‘@reduxjs/toolkit’; import gameBoard from ‘../features/ticTac’; import currentPlayer from ‘../features/currentPlayer’; import gameOver from ‘../features/gameOver’; export const store = configureStore({ reducer: { ticTac: gameBoard, currentPlayer:currentPlayer, gameOverSlice:gameOver }, });

ConfigureStore is an abstraction over the standard Redux create store function that adds defaults to the store set up for a better development experience. GameBoard, currentPlayer, and gameOver are the pieces of state that can be retrieved from the reducer. The code block above is for configuring the store. We can use the getstate store method to access data saved in the store.

In Closing

The redux state management tool is helpful in centralizing our app state while also providing us with tools to help debug and easily trace and find bugs that might be hard to discover.

While redux is a great state management tool, you should only implement redux in your app if you can conclude that your app needs a state management tool. For a full example of a working Redux app, check out this Github repository