DEV Community

Bentil Shadrack
Bentil Shadrack

Posted on • Updated on

React Hooks vs. Redux

In developing and application, Data management is an important concept used by developers to minimize potential errors by establishing processes and policies for usage and building a single source of truth for the data being used to make decision across the app.
In in this article, I will be discussing with you React Hooks and Redux and how they differ.

It is important to note that Redux and React Hooks should not be seen as the opposite of each other. They are different things, with distinct goals.

yeeeeesssssssss

React State Management

As your application grows, it is imperative to be conscious of how your app state is organized and how the data flows between your components. Redundant or duplicate state does not help give a single source of truth to your decision making data, which is a common source of bugs.

To handle data between separate components in React, developers use a practice known as prop drilling.
This is the act of passing data from a top level component till it get's to the child component you want to access it from.
Not only does this method requires writing extra tones of code, It also affects the architectural design of the app and also makes it difficult to debug when you encounter errors.

How

To curb this menace, Redux is used, An open source JavaScript library for managing application state.

React Hooks vs. Redux

Redux has been the go-to solution to developers when it comes to state management. To some extent, it works well for state management in React apps. However, because of its verbosity, it is a bit challenging to master, and the additional code required to make it function can add a lot of needless complexity.

On the other hand, installing other libraries or adding several files and folders is not recommended in app development. Thanks to React Hooks and the useContext API. As a result, handling global state management in React apps is made considerably simpler and clearer.

Redux

Redux is a predictable state container for JavaScript apps.
It helps you write applications that behave consistently, run in different environments (client, server, and native), and are easy to test. On top of that, it provides a great developer experience, such as live code editing combined with a time traveling debugger.

Terminologies in Redux implementation

Actions
Actions are objects that are used to send data to the Redux store. They normally have two properties: a payload property that holds the data that needs to be modified in the app state and a type property that describes what the action does.

const reduxAction = (payload) => {
  return {
    type: 'ADD_TO_CART',
    payload
  }
};

export default reduxAction;
Enter fullscreen mode Exit fullscreen mode

Reducers
Reducers are simple functions that carry out the behavior of the action. They begin with the application's current state, take action, and then return a new state.

Reducer
Store
The store is where the application's state is kept. In any Redux application, there is just one store:

import { createStore } from 'redux'

const store = createStore(componentName);
Enter fullscreen mode Exit fullscreen mode

React Context API

Context provides a way to pass data through the component tree without having to pass props down manually at every level.
It allows you to share data that can be considered global for a tree of React components, like the current authenticated user, theme, or preferred language.

Creating a context API

import React, {createContext} from 'react';

const myContext = createContext({ username: 'qbentil' });
Enter fullscreen mode Exit fullscreen mode

The above code snippet create a context API using the createContext from reactjs.
The createContext from react return and object with two important properties, Provider and Consumer.

const { Provider, Consumer } = myContext;
Enter fullscreen mode Exit fullscreen mode

The Provider component makes the state available to all child components, no matter how deeply nested they are within the component hierarchy whiles the Consumer consumes the data from the Provider without any need for prop drilling.

React Hooks

Without relying on component classes, React Hooks is the new method for handling state and life cycle in React components. It was added to the library in version 16.8, and its goal is to make the components less complex by transferring logic between them.

React Hooks provides an easy way of handling the component behavior and share the component logic.

The goal of the React Hooks feature is not to replace prior understanding of React terms like lifecycle, state, props, context, and refs.

Conclusion

Redux and React Hooks should be viewed as both complementary and distinct concepts. Redux can be used to assist you manage the application data in projects of greater complexity, even though the new React Hooks additions useContext and useReducer allow you to control the global state.

Both can be utilized if you're planning to construct an application. React Hooks features handle the local component state while Redux manages the global state and actions that can be dispatched.

Happy Hacking!

Bentil here🚀
Which of the state management tools mentioned is your favorite? Share your experience in using it below. It might be helpful to someone else too. I will be glad to hear from you in the comment section.

If you find this content helpful, Please Like, comment and share

Top comments (41)

Collapse
 
leob profile image
leob

If your app is moderately complex and needs a substantial amount of "global" state management, then I'd just go with Redux ... Context is not really THAT much simpler (you'll probably still end up writing the same kind of reducers and actions, etc).

The problem with Context is that it's not that smart about what to re-render, it will often just re-render the whole component tree - Redux does that a lot better, and in the end it's not really harder to use (especially not if you use the great Redux Toolkit, which means you're going to write a LOT less boilerplate).

Collapse
 
alexerdei73 profile image
AlexErdei73 • Edited

I haven't used context yet, but as I saw in code samples, it does not look much different from Redux, so you might be right. Redux is a powerful tool above a certain amount of UI complexity. If you had this kind of task to solve, I would just go ahead to learn a bit Redux. If you practice it without trying to memorize the pattern, you will be OK with it. You will realize that your part is just doing the same thing over and over again and it leads a very nice application pattern, which is loosely coupled code. It's easy to test and debug and Redux gives you invaluable tools for this too in the form of browser extension for time-travel debugging. The true difficulties and most of the pattern is hidden away from your eyes and buried in the library itself. If you wanted to touch Redux itself, that would require a very different level of knowledge and skills, but trust me, you couldn't do it better than those, who already done it. It's just better to learn how to use it at the beginning then some day you will be able to understand the inner working of the things inside too. Until that, just rely on the job of those experts, who wrote it for you.

Collapse
 
leob profile image
leob

Amen to all that ... and the Redux Toolkit vastly reduces the amount of boilerplate code that you need to write.

Thread Thread
 
qbentil profile image
Bentil Shadrack

Oh nice

Collapse
 
qbentil profile image
Bentil Shadrack

Awesome input
Thank you

Collapse
 
leob profile image
leob

Thank you too for the article ... and on top of that, Redux can aid in answering the eternal React problem "where the heck do I put my business logic?"

Thread Thread
 
qbentil profile image
Bentil Shadrack

Exactly😅

Thread Thread
 
alexerdei73 profile image
AlexErdei73 • Edited

The business logic is always outside of the UI logic either way or that way in the case of React. My app does not have business logic, because it's a huge React UI. A Facebook clone is just a huge UI. The problem there is how to connect it to your back-end. Other apps have a large amount of business logic, which can be quite complex. React won't help with this at all. The role of React is nothing else than simplifying the rendering of your UI. This itself can be very difficult in the case of a difficult UI and without a front-end framework can result a huge amount of inefficient DOM manipulation code, which can be very tricky. Tricky code is usually bad code too. The main point of a front-end framework is the simplification of this code. In the case of React your business logic can be simple vanilla JavaScript code, which is working on the React state. This way the UI reflects the results of your business logic. It's usually not a big issue to connect vanilla JavaScript code with your React UI, unless the global state of the UI has been scattered through all of the UI components. The important principle is the single source of truth. The global state should be kept in the root component, which is the point of connection as well. Redux makes it even more simple to keep the global state in a separate Redux store. It also gives the tools to connect your vanilla JavaScript code to the Redux store. This itself can be done without Redux too, but Redux makes it even easier. On the other hand try to connect your back-end nicely to the React UI. This is more difficult even in the case of a BaaS service like Firebase too. Redux can be a good help here. If someone is interested, how complex business logic can be connected with a React UI, I can show a great example. Check this project: react-tic-tac-toe. This is a simple tic-tac-toe game with a React UI. The connection point is the App.js file in the src folder. This project has a version without the React UI. You can find it here tic-tac-toe. You can compare these code wise. The UI is simple enough not to use React at all. You can see what difference React makes in the code. This app does not require Redux at all.

Thread Thread
 
qbentil profile image
Bentil Shadrack

Thank you Alex

Collapse
 
mukadas profile image
Mukadas Maltiti

Do I have to jump right into redux or I should use it only when I'm dealing with complex data in state?

Collapse
 
alexerdei73 profile image
AlexErdei73

I think you can jump into Redux right away, when you are comfortable with basic React. You should be able to use class components, function components, use State and useEffect hooks well. You should know how to do prop drilling as well to pass global state from your root components down to the child components. At this point you should learn some basic terminology and the software pattern, how Redux handles the global state with React. Don't worry about the boilerplate, it's not so bad by these days. You have redux-toolkit and react-redux libraries to make things relatively simple. It's relatively simple, but introducing this complexity only worth for huge UIs, like a Facebook clone for example. Redux docs are very good and written by Mark Ericson. Do his tutorial and you will be able to refractor your app by Redux.

Collapse
 
mukadas profile image
Mukadas Maltiti

okayy, thanks
I'll take a look at the documentation

Thread Thread
 
alexerdei73 profile image
AlexErdei73 • Edited

Applying Redux is a more powerful tool than simply applying the Context API from React to avoid prop drilling. Redux eliminates the prop drilling, but it does more. In my app for example it beautifully connects Firebase with the React UI. The app was made without Redux first. I used a library, which injected Firebase data into React components directly. Do not do it this way. Most of my components were full of code, handling Firebase. So the back-end handling code was scattered everywhere. This is very bad. Redux let me do that the right way, as Firebase could handle the Redux store separately from the React UI. The link of the app is Fakebook. You can have a look and if you were interested you can see the code on my github. It might be worth a full blog post, but I don't have time for it yet.

Thread Thread
 
qbentil profile image
Bentil Shadrack

Awesome👏👏👏👏

Collapse
 
qbentil profile image
Bentil Shadrack

Thank you Alex!

Collapse
 
arturasmckwcz profile image
Arturas Mickiewicz

As far as I know React Context actually rerenders all components in the way despite if they use or not the state. The only benefit is you don't need to do prop drilling in order to access it at some level. If you consider real state injection at any level you need to use Redux or any other real state management tool.

Collapse
 
alexerdei73 profile image
AlexErdei73 • Edited

Yes in the case of Context, the global state of your UI is still stored in a React component, usually in the root component (Single source of truth). In the case of Redux, the global state stored separately out of the React component tree, in the Redux store. The state can be connected with some hooks easily to any component in the component tree or the case of Redux even to any JavaScript code out of the React UI. Because of this Context is stricly capable of eliminating the prop drilling problem, but cannot really do anything else for you. It is a purpose built tool for avoiding that problem. Redux on the other hand eliminates the prop drilling problem too, but more powerful tool as it removes the state from the React UI and makes it possible easily to connect to any kind of JavaScript code. It also comes with a tool for debugging in the form of a browser extention. These things lift Redux above to the Context API, which is only enough to avoid prop drilling.

Collapse
 
qbentil profile image
Bentil Shadrack

Very true.
Thank you Arturas

Collapse
 
dikamilo profile image
dikamilo

What is complex data in state?

If you mean storing mostly responses from API, then consider React Query. Redux have advantages but in most cases is not needed at all and a lot of devs not use "unique" features that Redux provide.

Also, Redux can be used wrongly in app, especially in bigger project, when store is big, bad designed and devs don't know how to subscribe to state effectively.

Collapse
 
qbentil profile image
Bentil Shadrack

Thank you @dikamilo

Collapse
 
qbentil profile image
Bentil Shadrack

You can use it in your mini projects as well.

Collapse
 
tealover418 profile image
Stijn de Ligt

I am not a fan of Redux because of the boilerplating and obfuscating code.

Recoil is looking like a good alternative, is there anyone here that has used it for a production platform?

Collapse
 
elsyng profile image
Ellis • Edited

Recoil works great, it feels like React, much recommended. I've been using it, also in production, for a while now.

Recoil is about "simplicity", like React, like component based programming. Forget Redux, forget Context. Once you use Recoil, you won't go back. imho :o)

If you use Recoil, think atoms, keep the stores as small as possible. Just like: keep your functions, components, files, states and styling (hint: css-in-js, eg. styled-components) : as small as possible. Atomic.

Avoid larger and global scopes as much as possible :o)

Collapse
 
elsyng profile image
Ellis • Edited

Actually replying to @alexerdei73 :)
-- I think one good point is, Redux is a job skill. And actually it should not be. In most cases, the state management does not need to be an (extra) job skill.
-- Recoil (if you keep it simple) is very much like useState. If you need to hold some data for a single file, then you use useState. If you need it for several files, then you use useRecoilState. Otherwise they're kind-of the same, from a certain perspective. You can see it as part of React, just like useState is. It should not be an extra job skill. It is, and should be, just React.

And by the way, I think in many projects, one gets the freedom to choose which tools (eg. hooks) you are going to use.

Thread Thread
 
alexerdei73 profile image
AlexErdei73

Now I understand. Recoil is another library to sort out state management for React. Its purpose is like Redux', but according to you and their webpage it's really simple and React like. So it feels like a natural extention of React. It's a very sympatic idea to me. My only problem with it its popularity. Redux is the most popular tool and normally job requirement. Recoil might be the future tool.

Collapse
 
alexerdei73 profile image
AlexErdei73

Recoil sounds like a more complete solution than React with Redux for example. It must be great for your UI problems. Most of us learns frontend-frameworks to find jobs with these. This might be a questionable motivation, but recoil can be a bad choice with its limited popularity for companies. How it compares for Vue.js for example, which is much less popular than React, but people say similar positive things about it than you say about recoil. Vue is certainly popular enough to find jobs with it. How about recoil?

Thread Thread
 
qbentil profile image
Bentil Shadrack

Thank you for throwing more light on the

Collapse
 
qbentil profile image
Bentil Shadrack

Oh I see.
I will give it a try

Collapse
 
qbentil profile image
Bentil Shadrack

I haven't used it before tho.
I will check it out. Thank you

Collapse
 
gsichao profile image
gsi-chao

Thanks for the post, Inspired by the FLUX patterns and Redux, I recently create this starter template to create Stores using Only React Hooks and Context API.
github.com/gsi-chao/react-hooks-st...

Collapse
 
qbentil profile image
Bentil Shadrack

Awesomeeee🥳🥳🥳
Thank you for sharing

Collapse
 
ismailghedamsi profile image
ismailghedamsi

Should i use redux for managing multiple modals or using useReducer is enough?

Collapse
 
alexerdei73 profile image
AlexErdei73

I agree with the author. useReducer might be part of context, which I haven't used yet. Context can handle your modals as these are part of your UI. Redux is advantegous if you need to seemlessly combine your React UI with some other code, because it separates the global state from the UI and it makes it both easily connectable to the UI and other code in a loosely coupled way. If you already use Redux for other reasons, it's great to use it for handling your modals too. Modals only on the other hand do not justify the usage of Redux as these belong to the React UI.

Collapse
 
qbentil profile image
Bentil Shadrack

Thank you Alex❤

Collapse
 
qbentil profile image
Bentil Shadrack

useReducer is enough if you are not using redux at all in the project.
But if you are already using redux then I suggest you continue with redux for the modals as well

Collapse
 
reacthunter0324 profile image
React Hunter • Edited

Thanks for great article!!!
I've used redux for many years, but in the previous project, I used react-query including cache.

export const addNewDeviceToList = (key, updated) => {
queryClient.setQueryData(
key,
(old) => {
old.pages[0].data.data.data = [...updated, ...old.pages[0].data.data.data]
return old
})
}

Collapse
 
qbentil profile image
Bentil Shadrack

Oh great!
I am glad you like it

Collapse
 
candlepeter profile image
Isienyi Paschal Ejike

I am comfortable with React hooks and context API

Collapse
 
qbentil profile image
Bentil Shadrack

Great!

Collapse
 
ginxo profile image
Enrique Mingorance Cano

great article! they are indeed complementary stuff and they should be considered in this way
Thanks

Collapse
 
qbentil profile image
Bentil Shadrack

Yes sure🥳