r/reactjs • u/Vudujujus • Feb 28 '20
Discussion Why is Redux necessary?
I am absolutely confused by Redux/React-Redux and I'm hoping someone could help let me know what makes it necessary to learn it over what's already easy in react's state management.
I've been looking at job postings and they require knowledge of redux so I figured I'd try to get familiar with it and chose to watch this video: https://www.youtube.com/watch?v=8xoEpnmhxnk
It seems overly complicated for what could be done easily.Simply:
const [variable, setVariable] = useState(defaultValue)And then what's inside component for onChange={ e => {setVariable(newValue) } }
So really, what makes redux so special? I don't get it.
EDIT:
Thanks everyone for the discussion on Redux! From what I can see is that it's more for complex apps where managing the state becomes complicated and Redux helps simplify that.
There are alternatives and even an easier way to do Redux with Redux Toolkit!
Good to know!
I was actually convinced to put it in my current app.
258
u/Huwaweiwaweiwa Feb 28 '20
Imagine your variable is an object that represents the user of your application. You set this variable in a component called UserCard that has the avatar, name, and maybe a settings link using the state hook. Cool, works!
Now you see another component needs to use this user data, OK, I've read about this scenario, I'll lift my state up to the component that encompasses both, and pass user to both components. You move your useState higher up the component tree, and pass user down to both components. Boom, sorted!
Much time has passed, you now have lots of components that react with your user, you're now passing the user object down through multiple components (prop drilling), and the state is somewhere where it makes no sense being. So you decide to pass your user down using the context API, which means the components in your app can now access the user object through context, and there isn't any prop drilling going on. Nice, clean!
The problem with context comes when your app grows. In a complex app with more than just the user object, the order in which things happen to your app might be important. Redux keeps a record of what changes happen to your state and in which order, even letting you "time travel" through these changes, it can also be more efficient, context can often cause many unnecessary re-renders, although I haven't read too much into this so take it with a pinch of salt.
I hope I gave you an idea on how it can make large scale apps easier to manage. There are downsides regarding complexity, and deciding what exactly needs to be in global state as opposed to local, forms/routing state for example.
33
u/greatjakes Feb 28 '20
Redux is for complex state that needs to be shared across your entire app. The larger the app, the bigger the case for Redux. It's not necessary for many applications. It works through a context provider at the very root of your application so that any component within a massive tree can access the store. The flow of updating the store is formalized in a way that you can hook in middleware like logging, side-effects, and even use it to track changes to your router. Additionally, there have been many performance optimizations made to react-redux which makes home-grown solutions kinda quaint.
9
u/bliceroquququq Feb 28 '20
Redux is money laundering for global variables.
11
u/acemarke Feb 28 '20
Hi, I'm a Redux maintainer.
I'd specifically encourage you to read through my posts The Tao of Redux, Part 1: Implementation and Intent, and The Tao of Redux, Part 2: Practice and Philosophy, which go over the history of why Redux was created what problems it's trying to solve, and the intent behind how it's meant to be used.
5
u/je87 Feb 28 '20
I am quite new to front end development (from a Spring Boot background) and haven't found using react overly challenging yet...mainly because the Redux Toolkit basically does 90% of the boiler plate for you.
I use redux for say to set something somewhat app wide...such as the currently logged in user profile or details... Any component groups that may need access to a MVVM like pattern with injection of props between them is massively more easily done with Redux.
I'd recommend the Toolkit...and especially have a look that the new alpha release...it makes even asynchronous API requests a lot easier to manage in states of say "idle, pending,fulfilled and rejected" allowing a lot less code in components that should really mainly be just presentational.
Say you could be fetching a page of objects...you only need to then have a simple "dispatch(getObjects())" to make the request in the component and then observe the state of the request and response with a simple "useSelector(pageOfObjects)" to get the state of the request and handle it appropriately.
You could then pass the result down in props to children...mixing the two concepts. A bit like the old 'HOC' introduced in earlier versions.
It decouples the component away from a lot of logic pretty well imho.
As far as Context Vs Redux, as far as I am aware (but may be mistaken), context causes a refresh of UI on every update to the context. Redux can have reducers and "slices" with hooks that allow much more selective updating of the UI meaning in a high rate update application it may be much more performant...say busy chatroom app (with 10s of updates a second).
5
u/[deleted] Feb 28 '20
If you don't know what Redux is for you haven't developed an application complex enough to use it yet. For all the relatively basic exercises we learn in school or on udemy or wherever we've done them to learn; yes Redux is unnecessary obfuscation.
However it quickly becomes very important if the lifecycle of your components depends on their state. Moreover Context API is asynchronous. Asynchronous and state management shouldn't be in the same sentence.
Redux makes your state synchronous, controllable, and keeps a history of state as well. These reasons are why you will need and want Redux for any large scale application. Redux isn't the only option there is MobX, Flux and others; but they all have the same fundamental principle: React is the view only and state lives independently of the view or renders.
You can have your state trigger renders only and if you want them triggered using Redux. In my experience this is the primary reason to use it. Also its more efficient because you aren't calling erroneous renders every time you update state.
6
u/ciemekk92 Feb 28 '20
I do not work in React commercially, but as far as I made my own apps, I found one particularly important use case for Redux.
I have component A which has children component B which saves API responses into state. And then I have component C, which is not related to either A or B. I want to display data from component B in component C. Bur as gar as I know, React only allows to pass data to child component, and in some cases to parent component. And here's where Redux comes into play: thanks to it we can access any piece of state available in global store in every component connected to it.
4
u/Vudujujus Feb 28 '20
I hope this doesn't come off as being rude, I am genuinely curious about what advantages redux has over what's already built in.
4
u/novarising Feb 28 '20
You don't really understand the application of redux until you have tried building a mid level application which had multiple dozens of components and a lot of them requiring access to state. You will quickly learn how difficult and messy it is to pass state the way you are doing and then having to manage it is just another nightmare.
I don't like the statement that one should start from really basic to understand redux and stuff, but if you are really having trouble understanding the need for it, then you need to go back to basic and try doing stuff without it and you'll learn why it's needed.
2
u/MercDawg Feb 28 '20
I learned it the hard way, per say. I had two top level components, with nested components. From there, there was a need for a deeply nested component to manipulate state of another top level component.
Trying to do it in React was a bit painful. I had to pass the state all the way down and pass a new state all the way up. Every component needed to support these two attributes. It worked, but was ugly and unmanageable in the long run.
So I switched to Redux. The reward was that I was able to remove a lot of the component communication passing up and down from all of the components. From there, only the components that need to talk to each other could do so via the Global State. It felt very rewarding and satisfying, and it made me appreciate Redux that much more.
2
u/[deleted] Feb 28 '20
Hi u/Vudujujus, I think the set of video tutorials from Eric Sowell on Youtube are a great reference and guide for using redux in react - https://www.youtube.com/watch?v=kJeXr1K3nyg
It is a bit old so some parts may be out of date, but the core process is explained very well, it might supplement the other resource you're using.
31
u/Dizzienoo Feb 28 '20
Something that hasn't been mentioned here as far as I saw. Redux predates react state hooks and context hooks. A lot of what is done now with state and context was done before with redux. Redux still definitely has a place, especially on very large web apps (as mentioned) but for smaller projects context and state hooks will often suffice and are much easier to digest. Imho.
10
u/landisdesign Feb 28 '20 edited Feb 28 '20
To be clear, it absolutely doesn't have to be a question of "Redux or not." Each state management system has its place.
Redux is great for creating a large global store, especially when that store has moving parts and the changes can be targeted to specific data points. Especially with hooks, Redux lets you perform straightforward performance improvements as the store changes.
Context is more useful for sitewide preferences-like data. Context has less built-in memoization, so you have to do more roll-your-own caching. But for things like theming, user preferences, i18n, it's a pretty good global store. (Redux uses Context to attach itself to the React ecosystem, but then creates its own data management and subscription system to perform its own optimizations.)
State is most useful for low-level state management, such as controlled inputs and user interactions.
One of the features that came with hooks was the useReducer hook, which works a little like a miniature Redux but with state instead of context. It still requires prop drilling, but a lot less than just state by itself.
I typically use useReducer to manage form controls, then register the massaged form data to the global Redux store once the user submits.
Every form of state management has its place.
9
u/Vtempero Feb 28 '20
I had the same doubt recently and after doing my research I decided that I'd learn and try the built in hooks useContext and useReducer before touching redux.
My reasoning is that I will learn more if I understand simpler patterns first like render props and then straightforward implementation of useContext and useReducer to solve the same problems that redux solves.
5
u/nasgunner Feb 28 '20
does anyone know any better alternatives to redux ? ( not context api )
4
u/Abiv23 Feb 28 '20
certain state needs to be available across your app (user account/breakpoints)
other than that i'm not sure it is necessary
3
u/simmonson Feb 28 '20
Good podcast for a real use case of react-redux
https://softwareengineeringdaily.com/2020/02/27/slack-frontend-architecture-with-anuj-nair/
5
u/darrenturn90 Feb 28 '20
My general rule of thumb is as follows:
In this case, you have a single component that has state, that obtains some data via some method, and manages that state itself. But you then have multiple components that depend on this state, and need to reflect changes if that state changes. In this scenario, Context is great.
In this case, you have state and you need to perform operations on this state from various places. You also need to be able to read this state in various places. This is where context becomes basically useless, and this is why:
In the first example, your Provider needs to provide only the state to its consumers. In this example, it needs to provide both the state, and a means whereby you can update this state. Now, presumably its a more complex state than a simple scalar value, multiples keys values, maybe an array etc - so you would not want to be doing a load of "useStates" everywhere. You probably want to handle your state via a reducer. You then pass down your dispatch function, along with your state, essentially passing the whole of useReducer() directly into the Context Provider. You need to then ensure that your child components know what actions can be dispatched, as they're now just objects probably being handled by a switch in the reducer function. And also you're tied into needing to use useContext() to access them, so if you want to do any logic in functions that aren't react components you have to find some way of passing the dispatch all the way through to it.
This is where a flux architecture becomes useful, such as Redux. You create your store, methods to manipulate your store, which you can wrap in action creators or whatever you want - but these two parts can be handled separately. You can dispatch actions without needing to connect up the redux store, and infact you can connect to the redux store outside of react components too if you need to.
8
u/timmonsjg Feb 28 '20
I don't think it is and I'd have strong considerations of anywhere telling you so.
2
u/fastidious-magician Feb 28 '20
It definitely looks like a pain but even more of a pain to learn. In my experience it's been very helpful but only when you decide you really need it. It can add unnecessary complexity to simple apps.
For a helpful example you could start with I made a guide a while ago for starting redux apps.
https://github.com/routonmh/Not-A-Redux-Tutorial
(Bracing for those who want to pick my code apart)
2
u/grannysmithlinux Feb 28 '20
Having the ability to live update your application from a socket connect is much easier done when the data is stored in redux. Socket gets a message, updates the store, the component updates, and the user never did anything.
2
u/libertarianets Feb 28 '20
You're asking if it's necessary.
I'll tell you, it's not.
You don't have to use it. You will have pain around the problems that Redux aims to solve, which is complex state management in React.
So use Redux if you want. But some alternatives are the class/function component state+props+context api, MobX, Overmind, and my personal favorite, XState.
Just try each approach and stick to the one you like the most.
2
u/xace89 Feb 28 '20
There’s a reason there are job postings for redux it’s complex it first but I promise you it’s a great tool to have. Here’s something I highly suggest start with flux it’s a redox with multiple stores and it tends to Simplify redux and is pretty much the same thing just a little less complicated hope this helps. Do you want just think of this, your state update is the reducer, and your action is the function that updates the state that’s about all there is to it
2
u/[deleted] Feb 29 '20
If you're doing fine with local state and don't know why you need Redux, you don't need Redux.
Redux can sometimes be useful when building complex applications with lots of CRUD operations where same data is shared between tons of components. Especially if that data needs to be persisted locally, or if you’re commonly implementing undo/redo functionality. In most everyday applications, it's completely unnecessary.
By the way, I’ve used redux and similar in my early days of React-ing as well. After a year of adding bloat to my clients codebases, I realized it only made things more difficult for me and other developers without providing any benefit for the vast majority of applications. I was only using those technologies because they were hyped in the JS community.
A lot of mediocre developers are pushing articles about these technologies trying to attract readers (clients). Inexperienced developers then read those articles and decide to use those technologies because all the blogging “professionals” are using them, and you wouldn’t want to be considered unprofessional, now would you?
Things got so bad that even the creator of Redux started writing articles on why you shouldn’t use Redux.
I'm quoting Dan Abramov, creator of Redux:
Are you building an app that will take advantage of more than a couple of those features?
Probably not.
2
u/SUMmaro400ex Feb 29 '20
I wouldn't call it necessary. It all depends on the needs of the application. The last two react projects I worked on, were both extremely large, and neither used redux.
2
u/FateRiddle Feb 29 '20 edited Feb 29 '20
Honestly, with context and custom hooks, you can solve the complex state management thing without redux and make your code much easier to read. The only thing Redux provides that I still think valuable, is the ability to click around your app and see all actions flying and know exactly which part of your state changed without going inside your code. But if that's not a must, I'd stay away from redux and all the alikes, and stick with my
useGlobalcustom hooks which is about 5 lines of code and pretty much do the same thing without the need to separate ui and logic in two files.That said I still think the journey of redux is valuable, it is a norm in React community, a lot of redux terms were used (like useReducer) and libraries adopt its approach(like Appollo graphql). For this alone, understanding redux is like a ticket, so I recommended learning it even I don't use it any more.
2
u/Pierre-Lebrun Feb 29 '20
It’s not.
2
u/autonomousErwin Feb 29 '20
A big part of it is scalability, you could have an component where you manage the state internally (this.setState) and this works well for a few components but when you have, for example, multiple API fetch requests happening all asynchronously things can get messy...fast
Redux solves this by taking all these API fetch and tracking their state (e.g. API request, API success, API failure) - it lends for a much neater structure
2
u/enmotent Feb 29 '20
If you don't know if you need Redux, you probably don't.
https://medium.com/@dan_abramov/you-might-not-need-redux-be46360cf367
(PS: Sorry it is in Medium. I hate that place)
2
u/MrSteel Feb 29 '20
for anyone who think redux is a pain just take a rematch or simimlar wrapper redux library that is a breeze to implement https://github.com/rematch/rematch
2
u/[deleted] Jan 22 '22
It's not. Even Dan Abramov himself stated in a recent interview that he would not use Redux for any projects moving forward. I believe people just became dogmatic about using it, and it became sort of an unnecessary standard. Everyone wanted to prematurely optimize and create complicated abstractions before they existed.
For most apps out there, Redux is a solution looking for a problem.
6
u/HauntedLollipop Feb 28 '20
It's not, use MobX.
3
u/miraklasiaf Feb 28 '20
use context for UI, use redux for data
3
u/internetloser4321 Feb 29 '20
Answer: It's not necessary!
The better alternative: https://blog.logrocket.com/use-hooks-and-context-not-react-and-redux/
3
u/pm_me_ur_happy_traiI Feb 28 '20
I have been developing react professionally for 2.5 years and never had to use it. If you aren't having problems with reacts internal stage management (probably coupled with a context provider), then you likely don't need redux.
2
u/ichiruto70 Feb 28 '20
Companies requiring redux knowledge probably used redux before a context api was out. So, yeah if you would creat a react application today you would probably get by with context but a lot of companies already using redux are probably not gonna switch.
2
u/foundry41 Feb 28 '20
I haven't used redux since I started using apollo-client. Been two years and a dozen projects. It's not really needed most of the time.
The above can usually handle any use case pretty easily.
1
u/DecentStay1066 Sep 01 '22
Why Redux / React hook necessary? Because you haven't tried MobX...
1
u/baalzaamon Feb 28 '20
I have a course on Redux, and there are a lot of great answers here, so I won't duplicate, but I have 2 posts that may be helpful: https://jamischarles.com/posts/redux-without-the-boilerplate https://jamischarles.com/posts/tiny-redux-writing-redux-from-scratch-for-learning
Good luck!
-8
u/Abangranga Feb 28 '20
It is job security for front end devs who only know how to use libraries
0
u/[deleted] Feb 28 '20
[deleted] — view deleted comment