Why we need redux in react - javascript

I was done one small web application using ReactJS. It's easy to maintain and understandable. Now I learned Redux and plan to implement on it.
Its need some more stuff and extra things to do (To create store, Reducers etc.). I personally thought without redux the react is fine and easy to understand and maintain the states. Then why we need extra stuff (Redux)?

Reasons to use Redux:
Same piece of application state needs to be mapped to multiple
container components.
A good example of this is session state. When the app first loads, often information about the user needs to be shared with various components in the titlebar and each page. It’s likely these components don’t have any direct relationship so Redux provides a convenient way to share state.
Global strong textcomponents that can be accessed from anywhere.
It’s common to have components that live for the life of the application (for a single-page app this is every time the entry point is reloaded) that do things like show notifications, snackbars, tooltips, modals, interactive tutorials, etc. With Redux, you can create actions that dispatch commands to these components so, for example, if the code makes a asynchronous request to the backend it can dispatch a show snackbar action if the request fails. Without Redux, you would need some other event system or have to instantiate the snackbar component every time it gets used.
Too many props are being passed through multiple hierarchies of
components.
If a higher-level component is provided with a dozen props and uses only two of them, and the rest are passed down to a lower-level component, then consider refactoring with Redux. This scenario happens a lot with wrapper components that just provide layout styles, but don’t require a lot of data or configuration. It’s more practical to side-chain Redux directly into a lower-level component in this case.
State management using setState is bloating the component.
This is pretty subjective, but components that are over several hundred lines of code start to become harder to reason and maintain. Separating out the state management into a reducer breaks up the code and makes it more readable.
Caching page state.
When the user does some stuff to a page, then goes to another page and comes back, the expectation usually is to have the page in the same state. Some of this can be addressed by saving the page state in the backend and recalling it on page load. But, often things like search input values and expanded/collapsed accordions are just overkill to store in the backend. Since reducers typically initialize and live throughout the session, they can cache the page state so things remain the same.

Managing the state can be complex. Although react provides us with the state property but passing the state from component A to component B can be quite complex when the application grows. Here is a simple example which shows why do we need redux.
Consider an application with two functionalities "Users" and "Products".
Users have authentication implemented where they can sign-up and sign-in and the users can view the dashboard only when they are authenticated.
The other functionality "Products" also require user authentication information because the "Cart" operations will be accessible when the user is authenticated/signed-in. To get user authentication information at this part will require alot of state/props passing from "Users" component to a different section of the application "Products".
This is when Redux comes in picture, it provides a central store (stores entire application state) which is then available to the entire application.

TL;DR: Because you've done "one small web application". Not all web applications are small.
The most trivial examples of why you might need it include:
Sometimes unrelated components need to share state.
Sometimes state needs to be updated by things other than components.
Is it always necessary? Absolutely not. But breaking up state handling may confer advantages to non-small web applications, or complex interactions.
If all you have is a simple hierarchy of components, and things very low in that hierarchy never need to modify state that higher-level components need, then it brings in complexity that might not be necessary.
(Although even in those cases, it may be helpful; as always, "it depends".)

If you're building a house, you probably don't need a jackhammer even if you've learned how to use it.
You don't need Redux if your application's state is easy to manage without it.

As said in redux motivation page:
As the requirements for JavaScript single-page applications have
become increasingly complicated, our code must manage more state than
ever before. This state can include server responses and cached data,
as well as locally created data that has not yet been persisted to the
server. UI state is also increasing in complexity, as we need to
manage active routes, selected tabs, spinners, pagination controls,
and so on.
Managing this ever-changing state is hard. If a model can update
another model, then a view can update a model, which updates another
model, and this, in turn, might cause another view to update. At some
point, you no longer understand what happens in your app as you have
lost control over the when, why, and how of its state. When a system
is opaque and non-deterministic, it's hard to reproduce bugs or add
new features.
As if this wasn't bad enough, consider the new requirements becoming
common in front-end product development. As developers, we are
expected to handle optimistic updates, server-side rendering, fetching
data before performing route transitions, and so on. We find ourselves
trying to manage a complexity that we have never had to deal with
before, and we inevitably ask the question: is it time to give up? The
answer is no.
This complexity is difficult to handle as we're mixing two concepts
that are very hard for the human mind to reason about: mutation and
asynchronicity. I call them Mentos and Coke. Both can be great in
separation, but together they create a mess. Libraries like React
attempt to solve this problem in the view layer by removing both
asynchrony and direct DOM manipulation. However, managing the state of
your data is left up to you. This is where Redux enters.
Following in the steps of Flux, CQRS, and Event Sourcing, Redux
attempts to make state mutations predictable by imposing certain
restrictions on how and when updates can happen. These restrictions are reflected in the three principles of Redux.
But there are many cases where you won't need redux, it's important to understand what it does, and why you would need it.

I personally didn't use Redux in any of project I started over the last couple of year or so. I don't expect to use it in future either. Here's why.
Redux was revolutionary when it appeared in 2015. It brought two big ideas to React:
It combined action-based model of Flux with a concept of Reducer (It is in its name: "Red" "ux" = "Red"ucer + Fl"ux"). That Action - Reducer pattern instantly gained traction among React programmers.
It solved an application-wide state. Let's say we had certain data that we wanted to make available throughout the app. Before Redux the only reliable way to do that was to pass that data through props to child components... and then to their child components, and so on. Redux changed that. It allowed pieces of data to transcend the entire component hierarchy of an application without passing that data through props from one component to another. It also provided a convenient way to access and manipulate that application state from anywhere in the application.
Redux used a context API under the hood, which at the time was intended for React internal use only and was cumbersome to use.
Fast forward to 2019. A lot has changed. We now have hooks and the stable public context API which is ready for the prime time. An action - reducer pattern is now readily available via useReducer hook. We don't need Redux for that any more.
The modern React context API is simpler, more efficient than before and comes with hooks support. In most cases, wrapping your application state in a context is all you need to access it anywhere in your app.
So what about Redux?
My point of view that in a vast majority of cases you don't need Redux any more. Contexts and hooks get the job done most of the time. If you still think that contexts are not very friendly you may have a look at unstated-next library which is just a thin wrapper on top of the context API. That whole library is just 200 bytes!
However, plugging Redux into your project may be warranted if:
you want to take advantage of Redux middlewares such as redux-thunk
or you love Redux developer tools with their time-travelling ability.
In that case, make sure you know what you are doing. Redux magic comes with a price.
Redux is a complicated beast. It will bring a lot of complexity into your app. Some of that complexity is obvious while many other unobvious gotchas are hidden and waiting for you to trip on it. Think twice if you want to deal with that. Even then it is worth checking out alternatives such as MobX or react-sweet-state.
origin: You may not need redux

React ships with all the features you need to handle your state without a single additional library. Most of your application's states should not be global as they live just fine in a useState or useReducer or custom hook next to your components.
So before you dive into the world of advanced state management (e.g. Redux), consider using the tools React ships with out of the box.
If you are interested in learning a bit more about this, I'd recommend this article by Andy Fernandez: https://www.scalablepath.com/react/context-api-vs-redux

Related

Will hooks overthrown redux?

I've been searching for a while about React's hooks now, and one question became persistent in my head. Will hooks overthrown redux? This is a fairly old discussion so first a little bit of context :
State Management with React Hooks — No Redux or Context API
What do Hooks mean for popular APIs like Redux connect() and React Router?
redux-react-hook
A lot of people (React's team included) seens to think that redux and similars will just going to adapt to the new API, turning the HOC's approach obsolete, but my question is:
With custom hooks, use reducer, and a well thought logic why do I need Redux at all? I mean, isn't just more performatic to dispatch your actions to a single reducer? I've found a lot of material about it, but none of those seems to have a definitive answer (maybe because there aren't one?), so I would like to know what do you think about Redux's future?
It's really hard to say at this time. The redux team is actively updating the product to include some nice features. However, one of the creators of redux (https://github.com/acdlite) seems to be on a path to destroy his old applications in favour of new features in react.
That being said, Redux is a tested and known library that a lot of people are comfortable with. I do not believe it a bad idea to start a new project with redux Today, tomorrow, or in a year. Tech does not die overnight. if it serves a purpose it's going to live on.
However, I do think context and hooks are a great alternative to redux, but the community simply does not know how to use it yet.
Nope, definitely not.
I addressed this in my Reactathon 2019 talk on "The State of Redux".
Summarizing: hooks mostly offer ways to do the same kinds of things you could already do, like local component state and avoiding prop-drilling via context. If that's all you were using Redux for, then you probably didn't need Redux in the first place. But, hooks have their limitations, and there's lots of additional use cases for choosing Redux.
Also, note that we are currently working on designing a public useRedux()-type hooks API for React-Redux.
More than a year has passed since this question was posted.
I want to add that in my opinion Redux has lost some relevance...
2 players in my opinion have stolen a big share of Redux's position in the React market:
People have learned how to combine useReducer with useContext to
implement a much simpler solution and without third party
dependencies. With the advantage that the React team is behind it;
which means we will get constant improvements tightly integrated
with the React framework.
MobX has been growing it's user base. Mainly because it provides an observer pattern which requires much less boiler plate code than Redux. (This could be debated).
So even though Redux remains widely used for React projects I foresee this will be gradually reduced overtime... - no pun intended... well may be a little bit ;) -
Specially for green field development!

MVVM architectural pattern for a ReactJS application

I'm a semi-senior react and JavaScript developer, I've made several Universal react application.
Today our CTO told me: Do you use a software architectural pattern for your application?
I've no answer, He points to the Android team which use MVVM for their applications.
I'm searching greedy but not found a trend methodology or example for this situation. I've used Redux, Redux-Saga, React-Context and etc.
I don't know how to explain to our CTO or what is his answer?
Hence: Does a react app really need a software architectural pattern?
React itself is not particularly opinionated about software architecture. It is a library that facilitates the reusable component paradigm alongside guidelines for managing things like state and data sharing (props). At some point, Facebook described this as the V in MVC but have since moved away from that marketing to call it more abstractly A JavaScript library for building user interfaces.
Of course, the typical tooling associated with React apps does lend itself to something of an architecture when used together.
A couple of potential ways to think about it:
Simple React apps might be just "VVM" or "VC"
MVC is probably the better-known of the two in the development world. The key conceptual difference between a controller (C) and view-model (VM) could be boiled down into: a controller can have many diverse responsibilities, like listening for events and routing them in the right direction. It's the glue that facilitates the functionality of an entire application. A view-model, on the other hand, is simply responsible for gluing the current state of the data to the model.
So Facebook's original use of "V in MVC" could probably just as easily have been "V in MVVM" - the term controller makes more sense in backend development world.
A barebones React app, without Redux, that pulls data directly into components (e.g. fetch's in componentDidMount or leveraging GraphQL) with limited data wrangling of any kind could be called a simple "VVM" model.
View-Model (VM): Component-related code that manages simple state, passes data directly onto View, potentially passes data directly back from View
View (V): How the visuals look (JSX, CSS)
Add some complexity, and you could call it "MVVM"/"MVC"
If you toss in Redux, redux-saga, or even start doing crazy things with simple React component state, you're introducing model operations. There're at least two things this Model (M) can represent:
Actual business logic for your application
Storing and managing complex behavior in your client
Business logic is sometimes undesirable in practice: for example, if you have control over the server, it might be worth keeping all your business logic in one place (on the server) and just feed the UI what it needs to interact with the user. But if you have limited REST endpoints and need to do some wrangling (e.g. in your sagas, or within components), that'll be business logic.
Client behavior management is likely, especially in complex applications where you might be doing things like displaying different things to the user based on their session (e.g. they're an unregistered user vs. user vs. admin). You're probably doing this in any redux store interactions that are contained to use by only the client.
Disclaimer: discussing MVC, MVVM, etc. is likely to lead to many different opinions of exactly what they mean [1]. Above, I tried to draw parallels between common patterns I've seen and how they fit into MVC/MVVM, but there's so many different ways to approach it or more granular ways to think about it. I wouldn't get too hung up on putting a label on it as long as your system is easy to understand: modular, DRY, abstracted, etc. at levels that make sense for your use case and scale of development.
[1] Discussed in the some more length in answers and comments to this question
Vue 3 is MVVM:
Proxy Update
Model → ViewModel → View
Model ← ViewModel ← View
Update Event
And React:
setState Update
Model → ViewModel → View
Model ← ViewModel ← View
Update Event
The difference is only how the frameworks notify Model changes to the ViewModel.
A simple Web App does not require MVC, MVVM, does not require even React IMO.
Possible evolution of a simple ReactJS App that may see the need of MVVM/MVC/ if it tries to be PWA (Progressive Web App). In other words - if it tries to do some (application/domain) specific logic - offline and some other - online. This is natural point of thinking for mobile app development. Then, the information may be retrieved from the Local Storage or the IndexedDB (for the Web) or the Back-End/Rest/. Then, the separation of Model, Storage/Repository/Source Of INfo/ ViewModel/ or Controller/ and View will be natural and actually needed for all stuff to work correctly...

Is Redux.js a sufficient way to separate data from view in a React.js/Node.js hybrid application?

I am quite new to web programming. I've started developing a single-page web application using React.js with a Node server.
I've read the tutorial, played with boilerplates, and quickly I understood React would take care only of the view aspect. So I tried to put my data-processing functions with the export keyword in a JavaScript file so I could use them in my React components. But that way was pretty "dirty" and it didn't feel satisfying at all.
Then I looked for a way to effectively separate the model and the controller from the view, so that I could completely change the GUI with little effort, and thus allow the project to grow and multiple people to work on it at the same time.
I've came across this article explaining the Flux architecture, and I saw a major implementation to use with React.js was Redux.js. I was quite surprised that I didn't see it at first, and now I wonder how much frameworks one has to use when working with JavaScript and Web.
My question is simple : is Redux.js all I need to effectively separate data, treatments and GUI components ? Or did I miss something else ? Are there any other major architectures you would recommend ?
Many thanks,
Redux is generally used to contain all the data that your app needs. It acts like a store which can pass the required data to the components that actually needs the data. For example, if you need a particular data fetched from an ajax request to be distributed among two components, then redux is a perfect fit. Whether you need redux depends on how your app is structured. If you have an app with a large number of components and most of these require data from your server or api, I'd suggest you go with redux. Once you learn it, it's incredibly simple. And yes, redux is all you need to separate data from ui. To get a nicely formatted structure, put together all your ajax requests under a folder and export it so that you can call it from the ui component. And when you receive the data pass the payload to the redux store which will automatically pass it to all the components which are connected to that particular reducer. For details on how to connect react with redux, check out their documentation:
https://redux.js.org/basics/usage-with-react
Remember not to confuse the state mentioned in redux with the state in react. Redux state refers to the application state. Do check it out and if doesn't work for you, another alternative would be flux.

Is making each day a component in a reactjs calender bad?

I am trying to create a full page calender (All months are displayed one after the another in a single page). I am getting confused as to how to approach this, what I want to know is if making each day a component then a month component and the whole thing in a container bad? This code will go into production so I want good performance.
I also have to display some number(price for each date) with each date if that influences the decision.
I am looking to create a product that will look similar to React-Infinite-Calender but each day will also have a pricing detail as mentioned before.
Also is there a better way to approach this than the one I mentioned?
I don't think that modularizing your application is a bad idea or will affect your applications performance.
Splitting up an application in several components is what makes React this performant in the first place.
In your case it might be a good idea to determine if you need a component that is stateful or functional. From what you are presenting as your scenario I would go with an approach where the month (as one component) holds the state and then renders several functional components (as days) with the data (including the price tag you mentioned) passed to it via props.
There are several good ressources to be found online where you can read about structuring/modularizing your application with React components.
One of them is this post about structuring React apps: Structuring React apps
React is a component-based framework, so abstracting every item into separate component is the proper way. It allows you to have all the logic responsible for various elements incapsulated.
When creating your app, just remember to use map to generate the months and days inside. Doing to will quickly prove that your idea is correct.
Also, remember about passing props to children and stateless components, this will greatly improve your workflow and performance. Keep in mind though, that avoiding state can be harmful. Hoisting your logic up a few components will be a much bigger hit on your performance that using state.
Last, but not least, if you'll run into a problem with communication of components far from each other, try state management tools, like Redux.

State Management for Animations Using React Native and Redux

Background
I've been building an application using React Native & Redux to make an assessment over whether to use it for an upcoming project over Swift and going fully native.
I genuinely believe that Dan Abramov's techniques with Redux are a case of solid engineering. Not updating the state and having the view as a function of the state is great, and I'm very much on board with the idea. Where I'm coming somewhat unstuck is with throwing animations into the mix.
Scenario
More complicated animations require state management, for example, fading out a view, replacing the text and fading it back in. I'd only want to update the text halfway through the animation, and this is easy enough to do using local state and leveraging the Animated framework.
Say the text to be displayed is driven by the state, it'd be updated the moment the state is changed via an appropriate action & reducer combo, but for the sake of presentation I need it between these two animations.
An example of this would be selecting a record from a list, where there's an on-screen label showing the name of the selected record. Ideally you'd want to update the global store straight away, but perform a nice transition on the label itself.
My Thoughts
To my mind it makes some amount of sense to use 'local state' inside of components to deal with animations, and the main Redux store for more overall data or architecture state. The problem is this breaks the idea of the view being a function of the global state and I'm not sure that sits right with me.
On the other hand, managing animation sequences etc. by writing heaps of actions, reducers and cluttering up the store also doesn't feel clean.
The Question
I know React Native is in it's infancy, and not everybody is using Redux, but is there a generally accepted way of managing animations in this kind of scenario?
I've been developing React for only 9ish months, and so I'm probably a n00b compared to the likes of you Matt, and I can say without much hesitation that redux is awesome, but that it shouldn't replace internal component state in all circumstances. Especially for things like animations. You asked this yourself, but I ask again: why would this need to be in a global state? Redux is there to allow components across an application to get updated state when things happen throughout your application. That does not mean, however, that there should never be any state anywhere in your application except for in a Redux store.
A man much smarter than me said
If you feel pressured to do things “the Redux way”, it may be a sign that you or your teammates are taking it too seriously. It’s just one of the tools in your toolbox, an experiment gone wild.
Local state is fine....
The tradeoff that Redux offers is to add indirection to decouple “what
happened” from “how things change”. Is it always a good thing to do?
No. It’s a tradeoff.
What is this I'm quoting? What kind of blasphemous React developer could possibly say that Redux shouldn't be used for all things React??
I'll tell you who. The creator of Redux.
https://medium.com/#dan_abramov/you-might-not-need-redux-be46360cf367#.flb8fzjr8
TLDR Use Redux where it is useful and where it makes sense. It's awesome for what it's suppose to do.
But don't try to fit that round peg into a square hole.
I hope this is useful.

Categories