If you are getting into front-end development, you’ll probably come across Redux at some point. But what is Redux? In short, it is a JavaScript library that is most often used to manage the state of your web app.
According to our developers, Redux is a favorite for anyone working with React thanks to its predictability and the powerful tools that help you debug your code, but there are many other reasons we will address throughout this article.
At Trio, we focus on hiring the top 1% of applicants, ensuring that any Redux developers you get from us are not only efficient at state management using the library, but can also problem solve for real-world issues they may run into regarding implementation, state changes, and industry-specific challenges such as the documentation required in heavily regulated industries.
Our staff augmentation hiring model is by far the most popular, as you get the right amount of development talent on your team, acting as your employees, without needing to commit to them long term. However, we also offer outsourcing.
But before you decide to hire developers for global state management, let’s take a look at everything you need to know about the Redux library, how it can be used with React to manage state, and anything else that may be relevant to you.
What is Redux
Redux, as mentioned above, is a JavaScript library that you can use to manage application state. It is generally used to centralize state, before action, as a single source of truth for the entire state of the application.
The result of this centralization is consistent behavior, easy testing, and a very clear data flow architecture.
If you’ve been in the software development game for some time, you may realize that this sounds very similar to Flux. This is because Flex originally inspired Redux, which enforced unidirectional data flow and encouraged immutability.
If you are working with smaller applications, this may not be a very big worry, but when working with complex code with multiple components sharing the same data, Redux offers incredibly easy debugging and makes it easy to figure out how your application state changes over time.
Redux Building Blocks
There are several terms, or building blocks, that make up the Redux toolkit. These core concepts of Redux include the Redux store, actions, and reducers.
What is the Redux Store?
The Redux store is the heart of the application, which holds the application’s state and provides a way to change the state, dispatch actions, and register listeners.
In terms of code, the Redux store looks like the following:
const store = createStore(reducer);
What Are Actions in Redux?
Actions are essentially just a JavaScript object describing what happened. They need an action type property to pass data effectively.
One example would be something like the following:
{ type: ‘INCREMENT’ }
You can also pass data using a payload field.
What Are Reducers in Redux?
Reducers are a type of function. These reducer functions take the current state, add an action, and finally return a new state. They are critical, as they determine how the state should change in response to certain actions or situations.
Here’s an example of what that might look like:
function counter(state = 0, action) {
switch (action.type) {
case ‘INCREMENT’:
return state + 1;
case ‘DECREMENT’:
return state – 1;
default:
return state;
}
}
How Redux Works (Step-by-Step)
Let’s take a look at all the steps you will need to cover to ensure that Redux is used efficiently from the start. If you are running into any issues, you can use these steps to troubleshoot.
In practice, the Redux flow includes the action, reducer, store update, and finally UI changes in that order. For our examples below, we’ll be focusing on a console log to help you understand how everything will fit together.
Step 1: Install Redux
As with anything else, you need to install Redux before you can use it.
The most basic thing is to run the following command:
npm install redux
This will allow you to install Redux via npm.
Step 2: Create Your Project File
Once you have installed Redux successfully, you can create a project file. This will have to be a .js file since Redux is a JavaScript library (or a JS library).
This file name can be anything you want it to be, but we always recommend that you label files clearly so that you can refer to them later. Try something like reduximport.js or reduxsetup.js, as this will be your working file for the Redux setup.
Step 3: Import Redux
When that is done, you can import the createStore function from Redux.
const { createStore } = require(‘redux’);
Doing so will allow you to set up your store to get started so that you can start managing and altering your initial state.
Step 4: Create a Basic Reducer
You can now create a basic reducer to handle the counter state of your application.
function counterReducer(state = 0, action) {
switch (action.type) {
case ‘INCREMENT’:
return state + 1;
case ‘DECREMENT’:
return state – 1;
default:
return state;
}
}
Step 5: Create a Store
Now that all the basics are covered, you can create your first Redux store using the reducer:
const store = createStore(counterReducer);
As we have already mentioned a couple of times, this store will allow you to manage the state of your application, but will also give you access to methods like dispatch() (to dispatch an action) and getState().
Step 6: Subscribe to Store Changes
Once you’ve ensured everything works well up to this point, you can then use store.subscribe() to make sure that you are aware of any changes happening in the state of components.
The idea is to set up a callback that will run every time an action updates the state, so that you do not miss anything.
Here’s what that might look like:
store.subscribe(() => {
console.log(‘Current state:’, store.getState());
});
Step 7: Dispatch Actions
Finally, you need to actually make changes to the state of the components. The only way to do this is to make sure that an action is dispatched using dispatch().
store.dispatch({ type: ‘INCREMENT’ }); // State: 1
store.dispatch({ type: ‘INCREMENT’ }); // State: 2
store.dispatch({ type: ‘DECREMENT’ }); // State: 1
When you run the script, your output should be very simple.
Current state: 1
Current state: 2
Current state: 1
Integrating Redux with React (React-Redux)
While Redux can be used with Angular, Vue, Mithril, and many others, the most common pairing for web development is React and Redux. Likewise, the most common pairing for mobile development is React Native and Redux.
Integrating Redux with your React components is quite simple.
Reading from the State
To access your existing state in React, you first need to connect Redux to your React app by using the react-redux library and the useSelector hook.
That will look something like this:
const count = useSelector(state => state.counter)
If you are using class components or are not comfortable with React hooks, you can use the HOC-based approach with connect().
Changing the State
Changing the state is very simple after this and involves triggering actions with useDispatch. This is a hook that returns the dispatch function of your store, letting you call it inside the relevant component.
Here’s an example:
const dispatch = useDispatch();
dispatch({ type: ‘INCREMENT’ });
Advanced Redux Usage
There are plenty of more advanced ways that you can use Redux to help you manage state across your entire application.
Middleware
Middleware lets you alter the dispatch function by allowing you to hook into the Redux cycle between the action being dispatched and arriving at the reducer.
Usually, this lets you do things like log efficiently, catch errors, and even perform asynchronous actions like API calls.
Redux has a built-in applyMiddleware() function. To set up middleware successfully, you would need to use the function when you set up your store initially.
Here’s an example of how you can add redux-logger to automate logging for your dispatched actions.
import { createStore, applyMiddleware } from ‘redux’;
import logger from ‘redux-logger’;
const store = createStore(reducer, applyMiddleware(logger));
This is a relatively simple example. Middleware is more popular for handling asynchronous logic through something like Redux Thunk.
Redux Thunk
Redux Thunk is one of the most popular middleware packages out there. As we’ve just mentioned, it’s great for handling asynchronous logic as it lets action creators return a function instead of an action object.
Here’s how you would apply it when creating your store:
import thunk from ‘redux-thunk’;
const store = createStore(reducer, applyMiddleware(thunk));
This is not useful in and of itself, but when that function receives the dispatch and getState methods as arguments, it can be delayed, or dispatching can be conditioned.
Here’s how Redux Thunk fetches data:
const fetchUser = () => {
return async (dispatch) => {
dispatch({ type: ‘LOADING’ });
try {
const response = await fetch(‘/api/user’);
const data = await response.json();
dispatch({ type: ‘USER_LOADED’, payload: data });
} catch (error) {
dispatch({ type: ‘ERROR’, payload: error.message });
}
};
};
Using Redux in React Native
While we’ve mostly discussed web development, the relationship between React and React Native means you can easily use Redux for your mobile development.
Importing is quite simple:
import { Provider } from ‘react-redux’;
import { store } from ‘./store’;
export default function App() {
return (
<Provider store={store}>
<MainNavigation />
</Provider>
);
}
Alternatives and Industry Trends
While Redux is the most popular state management library or framework, there are definitely some competitors on the rise.
Why Zustand Is Gaining Popularity
While many of our developers still rely on Redux, many have familiarized themselves with Zustand to keep up with industry trends.
Zustand is incredibly lightweight and minimalistic, with a very simple API and built-in hooks support, which makes it ideal if you need something fast and scalable.
Many of our developers have said that you can’t possibly get any simpler than Zustand. Redux, on the other hand, needs a lot of boilerplate code, making it feel seriously over-engineered at times. Redux can also be very difficult to maintain thanks to this additional code.
When Redux Is Still the Right Choice
Redux has stayed popular for a reason.
While it may not be the simplest to learn or the easiest to work with, it is ideal for large-scale applications that need consistency. For this same reason, it is ideal when you are working with teams of developers.
Thanks to the large community, there are many different tools and add-ons you can make use of, including support for middleware.
If you need advice on whether or not to use Redux with your apps, or if you are looking for developers to help you use Redux in your apps, you are in the right place. At Trio, we start with a free consultation to figure out exactly where you are in the development process and what you need.
We do not provide one-size-fits-all solutions, but instead connect you with the best developers, hiring from places like LATAM and Africa to ensure that you are getting experienced developers in the most cost-effective way possible.
Ready to get started? Reach out to schedule your free, 30-minute consultation.