Mastering Redux: A Beginner's Guide to State Management
Written on
Introduction to Redux
This post serves as a straightforward introduction to Redux, designed to simplify your learning process. This is the first installment in a series where I will explain Redux and its practical applications in the most accessible manner possible. Let's dive in!
Understanding the Need for Redux
Before delving into any new topic, I like to consider its practical applications and the problems it can solve. So, why should we implement Redux?
Imagine you have a web application with seven pages, and you need the user's details—like their username and email—to be accessible on the first, fourth, and seventh pages. How would you handle this? You could enter the user’s information on the first page, then pass those props through each subsequent page until they reach the desired locations.
This approach can become cumbersome, especially if your application has a large codebase with numerous components. The practice of "prop drilling" can complicate your app's architecture and lead to performance issues.
So, what's the remedy? The answer lies in using Redux.
When is Redux Necessary?
According to Redux documentation, you should consider using Redux if:
- Your application has substantial state that is required in multiple locations.
- The state is frequently updated.
- The logic for updating that state is complex.
- Your application has a medium to large codebase that may involve multiple collaborators.
- You want to track how the state changes over time.
If your application fits any of these scenarios, Redux is the right choice for you.
What is Redux?
Up to this point, we've discussed the reasoning behind using Redux, but what exactly is it? Redux is an open-source JavaScript toolkit designed for managing and centralizing application state.
So, what do we mean by "state"? In this context, "state" refers to the values stored in the Redux store that we want to update or display—this could be a number, user information, or anything else relevant.
Redux operates through four key concepts: the store, reducer, action, and dispatch. That's all you need to grasp to get started!
Are you ready? Let's proceed.
Creating a Store
A store is simply a container for your application's state. An action triggers a particular event, while a reducer processes the action. Lastly, dispatch is a function used to send the action to the reducer.
Let’s go through a basic example of incrementing a number by one.
First, create your application using the command:
npx create-react-app myapp
After setting up your app, navigate into the directory:
cd myapp
Next, install the required dependencies:
npm install redux react-redux
With Redux and React Redux now installed, you’re ready to write your first Redux example.
Revisiting the store definition: The store is where all your state is kept. Let’s create the store and wrap it around your app. Insert the following code into index.js found in the src folder:
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import { createStore } from "redux";
import { Provider } from "react-redux";
let store = createStore();
ReactDOM.render(
<Provider store={store}>
<App /></Provider>,
document.getElementById("root")
);
If you read the above code carefully, you’ll see that we created a store and connected it to our app. The createStore() function initializes the store, while Provider makes it accessible throughout the application.
Now, let’s discuss actions. Recall our definition: An action specifies what needs to happen.
Create two folders inside your src directory: one named actions and another called reducers. Then, create a file named index.js in the actions folder with the following content:
export const increment = () => {
return {
type: "INCREMENT",};
};
This function instructs the reducer to increment the state, which is indeed an action.
Next, create a file named add.js in the reducers folder. This is where the logic for incrementing the state will be implemented, alongside defining the initial state as 0. Essentially, we are setting a condition that increases the state by one.
Your add.js file should look like this:
const add = (state = 0, action) => {
switch (action.type) {
case "INCREMENT":
return state + 1;default:
return state;}
};
export default add;
Now, create an index.js file in the reducers folder and add the following code:
import add from "./add";
import { combineReducers } from "redux";
const everyReducers = combineReducers({
add: add
});
export default everyReducers;
Here, we import our add reducer to combine it with any future reducers, allowing us to manage all reducers from a single location.
Now, let’s connect the reducer to the store. In the index.js file located in your src directory, import the reducer and pass it to the store:
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import { createStore } from "redux";
import { Provider } from "react-redux";
import everyReducers from "./reducers/index";
let store = createStore(everyReducers);
ReactDOM.render(
<Provider store={store}>
<App /></Provider>,
document.getElementById("root")
);
Finally, let’s display it in our app. Open the App.js file in the src folder and insert the following code:
import React from "react";
import { useSelector, useDispatch } from "react-redux";
import { increment } from "./actions/index";
import "./App.css";
function App() {
const add = useSelector((state) => state.add);
const dispatch = useDispatch();
return (
<div>
<h1>Increment the count: {add}</h1>
<button onClick={() => dispatch(increment())}>+</button>
</div>
);
}
export default App;
As mentioned earlier, dispatch is a function that sends the action. The dispatch(increment()) line triggers the increment action, while useSelector() retrieves the current state from the store to display it in the <h1> tag.
And there you have it!
Conclusion
I hope you find this guide helpful. To elaborate further, you can manage state using various libraries like Context API, Easy-Peasy, Redux Toolkit, and others. However, I wanted to ensure you understand the basics of Redux first.
In the upcoming posts, we will explore Redux Toolkit in greater detail, and I will provide additional examples to enhance your learning experience. If you have any questions, feel free to leave them in the comments, and I’ll do my best to assist you.
Don’t forget to follow me for updates on the next post!
If you're interested, you can download my eBook for free or for a nominal fee.
For more content, visit PlainEnglish.io. Sign up for our free weekly newsletter and connect with us on Twitter, LinkedIn, or join our Community Discord to become part of our Talent Collective.
Additional Resources
This video tutorial provides a comprehensive introduction to Redux from scratch, guiding you through the foundational concepts and practical implementations.
This full course on React and Redux is tailored for beginners, focusing on the Redux Toolkit to simplify state management in your React applications.