- Development
Context API vs Redux – which should you choose?
Which is better, Context API or Redux in React projects? The answer to this question must be clarified. Although, it is often heard that Redux is preferred in complex projects. But what does it depend on?
Firstly, you must start with what component state management looks like in both technologies. What tools are used for this, and how do we distribute data in the Context API and Redux? Let’s take a closer look at these issues further.
Table of Contents
What is application state management?
The application state is a place to store code and is the standard part of all views. Based on this data, React renders the application and takes care of the update in case the data changes.
Front-end state management is a logic that stores and refreshes current data. This includes information about option button highlighting, user authorization, etc. Or in other words, it ensures the completeness of business transactions – storing user interface input and synchronizing it between pages, back-end, and front-end parts.
This article discusses the main differences in managing application states using contexts or Redux. However, we will start with how data is distributed in React.
How can data be distributed?
The simplest way to transmit data from parent to child in a React application is to pass it to the child via props, which are arguments passed to components as objects.
Props drilling
An extended module has many sections. Using the “props drilling” technique, we pass data from the top of the module to another item inside. Any change of state or props in React causes it to “re-render,” i.e., re-render the content (having a “to do” list with five items, we add a 6th item to that list). Then React will re-render the entire list once again because we changed the “list” props. When we use drilling props, every change of the props upwards causes a refactoring of the component to which these props are passed.
Time before React 16.3 – Before React, developers created the Context API in practice.
The graphic shows a typical React application framework. “Article” is rendered by “Content,” “Content” is rendered by “Main,” “Main” is rendered by “App,” and “State” is plugged into the app.
A problem before the React developers introduced the Context API involved having some “State” of the application and wanting to pass it on to the “Article.” This could only be solved by passing it through props one by one.
However, the problem develops when a deeply nested descendant element requires data from a component higher up in the tree. If we desire the code to be more readable and the application to be easier to modify, it is better to give up “props drilling.” You should only pass props a maximum of two or three levels. So that later, when changing the application’s component tree, there is no confusion, not knowing which props we passed to which component. We have state management solutions such as Context API and Redux to solve the problem of props drilling.
What is the Context API?
Context API is a built-in React tool that doesn’t affect the package’s final size and is integrated by design. It’s designed to share the application state, allowing us to manage the state of our application not just by passing props down but by creating containers that hold our state enabling us to pass the state down in the component tree to anywhere in the application.
In Context API, we create a way to update and retrieve “state” ourselves. Context API allows sharing of data within a module between its components.
Any change of state in a component that uses “useState” locally, or a change in the context that the component subscribes to, results in a re-render of that component. So it should instead contain static data.
What is the Context API all about?
We create, for ourselves, a context – a place to store state and relay state to other components in the form of “providers.”
Context allows us to “wrap” the components we want access to and easily pass data values to a state lower in the component tree. The context API will enable us to manage the application tree better, passing data through the component tree without manually passing props at each level.
We can have several contexts that are separately responsible for individual issues. This allows us to control how our application behaves when the application renders for particular data changes.
When to use Context API?
There are two situations when it is worth using:
- Data must be available in different components at multiple levels of nesting. It is always worth asking yourself: is the data I need available in various components and levels?
- There is no way to configure the component tree differently to avoid the “global” state.” Changing the components’ composition and moving the state higher or lower is enough to solve a given problem in the application.
Context API usage example
Below, we demonstrate the creation of a sample context for “user.” Here, we have information about the user’s username, accesses, groups, selected themes, restrictions, or password change requirements.
Redux – what are its characteristics?
Redux is an open-source JavaScript library for state management that implements its Flux architecture. It is best suited for extended applications. What Redux is can be illustrated by an example. It resembles a large sliding cabinet. In that, it contains everything about the application. It is divided inside into shelves. Still, one who observes changes in Redux observes the whole closet, not one shelf.
Redux runs throughout the application and allows you to indicate “what” and from “which shelf” you want to read. As such, you can access the “store” from any component. This works smoothly, providing the middleware is ready, and there is complete control over downloads, states, etc. On the other hand, it is not always efficient because any change in the “store” causes everything to refresh, causing it to run slower.
From an architectural point of view, Redux helps keep project folders and files in order. It makes it easier for developers to understand the application’s structure and introduce newcomers to the project (provided they have prior knowledge of Redux). Its components include a global store, reducers, actions, and extensions, which act as middleware. We wrote more about it in the article below.
Is it possible to code in React without Redux?
Yes, it is possible. The only problem is that Redux has pushed out many things, so we will be responsible for distributing data in the React component tree. This forces us to keep performance issues in mind.
When does Redux apply, and when does the Context API apply?
It all depends on your specific use case. Both Redux and Context API help you avoid passing props sequentially in the component tree and allow you to plug directly into the application tree with a component.
▶️ Context API
Context API distributes data more locally. It is best suited for data operations involving high-frequency state updates (be defined locally in “useState”). Context is a mechanism for sharing values in a nested component subtree, not an approach to state management. This means you must write any state management logic needed to define the value sent to the context provider. For example, writing individual modules, such as a router or form handler, that are airtight and easy to test is useful. Comparably, the context API does not manage the application’s state.
Context API Features:
- Built-in tool provided by React
- Requires minimal configuration
- Works on static data that is not refreshed or updated frequently
- Adding new contexts requires creating them from scratch
- Debugging can be problematic in the highly nested structure of React components, even with a developer tool
- User interface logic and state management logic are in the same component
▶️ Redux
Redux requires adding more libraries to the application package. It is used when, for example, we want to complete modifications from remote components, communicate them with each other or share their state. Redux’s job is to hold the state – it renders the React application, and after the first rendering, it is said to “re-render.”
Features of Redux
- Additional installation is required, increasing the final package size
- Requires extensive configuration to integrate with a React application
- Works with static and dynamic data
- Easily add new data/activities after the initial setup
- Powerful Redux Dev Tools make debugging easy
- Facilitates code organization by providing separate user interface logic and state management logic
Summary
When deciding which application state management solution to choose, you first need to estimate your project’s size. This is essential so that as your application grows more extensive, you don’t have to rewrite everything from Context to Redux. Knowing which data needs refreshing and how often to do it is also helpful. Typically, we choose Redux for global state management if we work on a larger, complex project. If the project is smaller, or we focus on encapsulating modules, it is worth using the Context API.
At Studio Software, we work with you in mobile and web application development. Our engineering team constantly explores new technologies to improve the development process as well as the end user’s digital experience. Contact us to learn more about how we can help with your project.