redux or context

Redux vs. React Context: Which Should You Use?

22 Oct 2020

Development

Redux has been the go-to solution for state management since its conception in 2015. “You should use Redux” became such a universal truth, that so many started using it without really understanding why. And there are situations where Redux isn’t the best option. Some started to look for alternatives, including adopting other state management libraries or creating their own.

The widespread use of Redux gets even funnier when you consider the fact that the creators themselves (Dan Abramov and Andrew Clark) used to say that you might not actually need Redux. It’s important to understand what you can do with it before you stick it in your programming tool belt. Especially since there’s another solution that works great not as a competition, but rather as a supplement: React’s API interface!
The origins of SPA, a single-page application, go back to 2013 and the creation of the React library, used by Facebook. One of its biggest advantages was performance, achieved with VDOM.

Before we talk about React, you need to know two more things.

What is state management and why would you need it?

State management is the repository for the current state of the app and its data. It’s a common part of all the views. For example, in the case of user data; the avatar, the full name, etc. are stored in Redux.

Front-end state management is a kind of logic that stores and refreshes current data, such as the information about the options button being highlighted, about the authorization of the user, etc. Or, if we were to put it in a more abstract way, it makes sure that business transactions are complete – by storing input data of the user interface and synchronizing it across the pages, back-end, and front-end parts.

It’s also helpful in drawing a line between the business and view layers. This makes the app run faster without having to load the same elements all over again – they’re simply stored in Redux.

What is Flux architecture?

When introducing React, Facebook also shared a new concept of one-way data flow: Flux. It’s a general concept rather than a specific implementation, popular in front-end applications created with React or Vue. Facebook recommends using Flux for SPA projects—thus the widespread support of this solution found in many libraries.

Is Redux still relevant? And what is it anyway?

Redux is an open-source JavaScript library for managing application state. It works best in extensive, sprawling applications. However, to utilize it properly, first you need to prepare. Everything should go smoothly as long as your middleware is all done and you have full control over fetches, states, etc. In Redux, you don’t have to fetch everything all the time. This is the reason why Redux remains the most popular flux-based tool for state management.

From the architecture point of view, Redux helps maintain order in the folders and files of the project. It helps programmers understand the application’s structure and introduce new people to the project (providing that they have previous knowledge of Redux). Its components are: global JS object, reduction functions, actions and subscriptions.

The pros of using Redux

  • It’s widespread, so there’s an active community that can help you.
  • It’s easy to test.
  • There’s a good React Redux package for integrating React.
  • Good debugging, allowing you to log states and actions.
  • Nice code structure – Redux apps usually have similar architecture, so experienced programmers can easily switch to another project.
  • It’s designed for use with frequently updated data.
  • Redux eliminates unnecessary re-renders and the view refreshes when changing a specific object in the store.
  • Redux has access to middleware for async actions, but only when we use, for example, redux-thunk or redux-saga and expand the store with this functionality.

The cons

  • It’s not built-in React, which increases the ultimate size of the package.
  • Even if used with Redux Toolkit, it can be confusing for beginners due to its hidden logic.
  • It requires more configuration than Context API, and there’s more terminology to learn.
  • Problem with large boilerplate (this can be solved by using Redux-Toolkit).

Here’s an example of how Redux is used in a Todo List app

Initialization:
the entire Redux setup with an initiated Todo list and a provider that receives this configured store:

Reducer:

Action:

The component connected with Redux:


mapStateToProps
this function determines which data is injected into the Todo List display component.

mapDispatchToProps – this function determines which actions are injected into the component and which can manipulate the data from this state.

What is Context API of React?

Context API is an intelligent built-in function for solving issues with sharing data between nested components that are not linked directly. It is built in to React and doesn’t require any additional building. All the “uses” here are ReactHooks, bases for functions that simplify data positioning within components. The component blocks are Context Object, Context Provider, and Context Consumer.

Integration of Redux with React-Redux

To use Redux in React, you need to connect the React-Redux library.
Redux and React-Redux are two different things, Redux allows you to manage the state of the application and possibly inject middleware using other libraries (e.g. Redux-Thunk) and it does not matter whether it is used in an application written in Angular Vue or pure JS.
Only React-Redux allows you to inject store into components, it makes sure that these components are not rendered unnecessarily. Important to mention, React-Redux partially uses Context-API.

The pros of using Context API

  • Simple to use.
  • Great for static data as it doesn’t update frequently like Redux.
  • Low entry barrier due to minimal configuration. Just create a context (sometimes also a package component).
  • Good documentation for the React segment.
  • The app can include multiple local contexts for separate logic tasks.
  • Out-of-the-box.

The cons

  • Not designed to use with frequently refreshed or changed data.
  • The maintenance of complex apps can be difficult, especially if we use non-standard solutions.
  • Improperly passed data / parameters to components can make it difficult or impossible to reuse them outside of React-Context.

Lookout, it’s a trap!

At the time of writing this article, the interface of Context API isn’t optimized for high-frequency updates. You can face this issue when trying to move to React Context internally in your package. The new context is ready to use in unlikely, infrequent updates such as localization/theme. It’s advised to use it in the same way as the old context, for static values. It is not recommended for general state management.

Here’s how Context API and Hooks were used for a ToDo app in ReactJS

Initialization of the Context API provider, with all subordinate components of the provider linked to the Context API data:

There is context and an implemented provider with a state (and a function that modifies this state – toggleTodo). It is then transferred to the components that are the children of the provider:

This component gets data and a modifying function through hooks. Here’s an example of standard use:

Here are some examples of uses in specific cases

1. We used Context in the Metrix project. Metrix is a tool for analyzing data based on demand, supply, and freight rates of the European market. The frontend queries the backend using GraphQL’s „query language,” and displays data in the form of graphs, statistics, and maps. The data is visualized through React and supports libraries like Recharts, D3, Leaflet, and OpenStreetMap. We use Context to store the ‚user’ – the login data, avatar, etc. The amount of data is small, the data must always be up-to-date so there was no need to use Redux. Read more about the project >>

2. In trans.info, our other case, we used only Redux. This project involved large quantities of data, articles, commentaries, likes, dislikes, and user data. Managing the state of such a complex app is a job for Redux.
It’s a database and a powerful maintenance tool for the front.

Will React’s Context API replace Redux?

In our opinion, it won’t. Many projects are running on Redux and no one in their right mind is going to rewrite them for React. Both solutions will exist next to each other.

If you use Redux only to avoid transferring props, Context can replace it. But if that’s the case, you didn’t need Redux in the first place. There’s nothing like Redux DevTools in Context, there’s no state update tracking, middleware for adding centralized logic or other powerful capabilities of Redux.

Context is just a mechanism for sharing values to a nested subtree of components, and not an approach to state management itself. What this means is that you have to write any state management logic you need to define the value that is transferred to the context provider. Usually it happens through the React component state, but the point is that Context itself won’t manage the state for you.

Should I choose Context or Redux?

Let’s sum it up. Redux allows the use of a third-party library so that middleware can be accessed. It’s designed for use with frequently refreshed data. There’s an active community around it. There are frequent updates.

Context is quickly implemented and offers a lower entry barrier. It’s easy to expand it, but hard to switch from Context to Redux. Context is built into React, you don’t have to install it or get any additional dependencies. You get a smaller package and better project maintenance. The API interface is also relatively simple to use, once you get a hold of it. You don’t need packages like Redux-Thunk for async actions.

Redux is just a library that can be used in JavaScript, but to be able to use it, e.g. in React, you need to integrate with React-Redux, thanks to which we will have the so-called Provider (it is also in Context-API) which will wrap the entire application and give us additional functionalities (HOC connect or useSelector hook) thanks to which we will be able to extract data from the store anywhere. It will ensure that the component only re-renders when a specific object in the store changes. Context API does not provide this and that is its biggest downside (this problem can be solved in short by using several providers, using memoization. Both involve the use of boilerplate code – but we could create a separate article about solving this issue).

So what should you choose? Context or Redux? First, estimate the size of your project or app. You don’t want to find out later that it increases in size and you have to rewrite it from Context to Redux. You need to know which data needs refreshing and how often. You need to know what your project actually is. If we work on a larger, complex endeavor, we choose Redux for global state management. If the project is smaller – Context is the way.

At fireup.pro we work with you to recognize, understand, and help you achieve your objectives. We create a feedback loop that enables us to improve quickly and effectively. We’re concerned about both the customer and employee sides of the applications you implement. For us, it’s the only way anyone can be successful in business.

Share on:

Facebook fireup
Facebook fireup
Twitter fireup