Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
React 16.3.0 was released and the Context API is not an experimental feature anymore. Dan Abramov (the creator of Redux) wrote a good comment here about this, but it was 2 years when Context was still an Experimental feature.
My question is, in your opinion/experience when should I use React Context over React Redux and vice versa?
As Context is no longer an experimental feature and you can use Context in your application directly and it is going to be great for passing down data to deeply nested components which what it was designed for.
As Mark Erikson has written in his blog:
If you're only using Redux to avoid passing down props, context could
replace Redux - but then you probably didn't need Redux in the first
place.
Context also doesn't give you anything like the Redux DevTools, the
ability to trace your state updates, middleware to add centralized
application logic, and other powerful capabilities that Redux
enables.
Redux is much more powerful and provides a large number of features that the Context API doesn't provide, also as #danAbramov mentioned
React Redux uses context internally but it doesn’t expose this fact in
the public API. So you should feel much safer using context via React
Redux than directly because if it changes, the burden of updating the
code will be on React Redux and not you.
Its up to Redux to actually update its implementation to adhere with the latest Context API.
The latest Context API can be used for Applications where you would simply be using Redux to pass data between components, however applications which use centralised data and handle API request in Action creators using redux-thunk or redux-saga still would need Redux. Apart from this Redux has other libraries associated with it like redux-persist which allows you to save/store data in localStorage and rehydrate on refresh which is what the Context API still doesn't support.
As #dan_abramov mentioned in his blog You might not need Redux, Redux has useful applications like
Persist state to a local storage and then boot up from it, out of the box.
Pre-fill state on the server, send it to the client in HTML, and boot up from it, out of the box.
Serialize user actions and attach them, together with a state snapshot, to automated bug reports, so that the product developers
can replay them to reproduce the errors.
Pass action objects over the network to implement collaborative environments without dramatic changes to how the code is written.
Maintain an undo history or implement optimistic mutations without dramatic changes to how the code is written.
Travel between the state history in development, and re-evaluate > the current state from the action history when the code changes, ala TDD.
Provide full inspection and control capabilities to the development tooling so that product developers can build custom tools for their apps.
Provide alternative UIs while reusing most of the business logic.
With these many applications its far too soon to say that Redux will be replaced by the new Context API.
If you are using Redux only to avoid passing props down to deeply nested components, then you could replace Redux with the Context API. It is exactly intended for this use case.
On the other hand, if you are using Redux for everything else (having a predictable state container, handling your application's logic outside of your components, centralizing your application's state, using Redux DevTools to track when, where, why, and how your application's state changed, or using plugins such as Redux Form, Redux Saga, Redux Undo, Redux Persist, Redux Logger, etc…), then there is absolutely no reason for you to abandon Redux. The Context API doesn't provide any of this.
And I personally believe that the Redux DevTools extension is an amazing, underestimated debugging tool, which justifies by itself to keep using Redux.
Some references:
Redux Is Not Dead Yet!
You Might Not Need Redux
Do React Hooks Replace Redux?
I prefer using redux with redux-thunk for making API calls (also using Axios) and dispatching the response to reducers. It is clean and easy to understand.
Context API is very specific to the react-redux part on how React components are connected to the store. For this, react-redux is good. But if you want to, since Context is officially supported, you could use the Context API instead of react-redux.
So, the question should be Context API vs react-redux, and not Context API vs redux. Also, the question is slightly opinionated. Since, I am familiar with react-redux and use it in all projects, I will continue to use it. (There is no incentive for me to change).
But if you are learning redux just today, and you have not used it anywhere, it is worth giving Context API a shot and replace react-redux with your custom Context API code. Maybe, it is much cleaner that way.
Personally, it is a question of familiarity. There is no clear reason to choose one over the other because they are equivalent. And internally, react-redux uses Context anyways.
The only reasons to use Redux for me are:
You want a global state object (for various reasons, like debuggability, persistence...)
Your app is or will be big, and should scale to many developers: in such case you probably need a level of indirection (ie an event system): you fire events (in the past) and then people you don't know in your organisation can actually listen to them
You probably don't need the level of indirection for your whole app, so it's fine to mix styles and use local state/context and Redux both at the same time.
If you need to use middleware for various purposes. For example logging actions, error reporting, dispatching other requests depending
on the server’s response, etc.
When data coming from multiple endpoints influence single component/view.
When you want to have greater control over actions in your applications. Redux enables tracking actions and data change, it
greatly simplifies debugging.
If you don’t want server response to directly change the state of your application. Redux adds a layer, where you can decide how, when
and if this data should be applied. The observer pattern. Instead of
creating multiple publishers and subscribers across the whole app, you
just connect components to Redux store.
From: When to use Redux?
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
Hello I am learning micro front end architecture. Consider I am working on e-commerce application where I have four verticals - Home, Account, PLP&PDP and Cart&Checkout.
My understanding is that each verticals will have their views, actions, reducers, sagas, store. Here we will have 4 redux store.
My question is there are couple of things like user profile reducer which might be useful to shared across all these micro front end apps. Here using 4 redux store is good idea ?
What is the correct way to handle this in react web app ?
There is no standard template solution for your question, its all need based. I am sharing how I worked on similar project structure and converted large monolith to Front & Back end micro services. FE is developed using different technology mix of Angular, React and Vue. We are using https://single-spa.js.org/ for management of different modules and created a parent app(container) in React and child frames as separate app using Angular and Vue. Data sharing management is done using mix of cookies/local storage and redux. Sharing of data between child and parent app is using Post Robot https://github.com/krakenjs/post-robot. We are running this structure in production from last 1.5 years and it is scalable solution.
In my experience your better off having one redux store that it managed at the framework level of your micro frontend that is namespaces for each of your micro applications. As each app is loaded in it can dynamically load in reducers, middleware and data.
The reason for taking this approach is that you will inevitably end up with some data that needs to be shared between different micro applications and this is much easier when you have a single store.
Check out this project from Microsoft that makes this a pretty simple thing to do now.
https://github.com/Microsoft/redux-dynamic-modules
Their are a number of other solutions to load different things into your store dynamically
https://github.com/markerikson/redux-ecosystem-links/blob/master/reducers.md#dynamic-reducer-injection
You have rightly divided the micro-frontends into Home, Account, PLP&PDP and Cart&Checkout and these will have their own store which will allow you to maintain them separately.
However, the catch is that they should be making service calls separately and maintain their store for that.
Now this way, the userProfile will be irrelevant to the Product Listing Page and Product Details Page. Same case with the Cart and Checkout Components. They might require a token to make some API calls, but that value can be fetched from the localStorage.
The other alternative would be to have a single Store and pass in functions to the respective micro-frontends for the actions. However, that complicates your application and moves towards a monolithic approach , defeating the purpose of a MFE architecture.
Refer to this link to checkout the basics
https://martinfowler.com/articles/micro-frontends.html#Cross-applicationCommunication
As a side-note, using Custom Events is also effective when it comes to communication between MFEs but that is preferable in cases where there is a large set of interactions required between projects.
Refer:
https://developer.mozilla.org/en-US/docs/Web/Events/Creating_and_triggering_events
If some of your redux stores needed to be shared across your application, then just create a seperate package out of that redux store using monorepo with yarn workspaces.
You can install that store as a seperate package and just use it by defined package name.
For more on this topic, please have a look at this Yarn Workspaces website.
https://classic.yarnpkg.com/en/docs/workspaces/
Also, using 4 redux store is not that bad as long as your micro frontend is supposed to be a self contained application in itself. But if the data is being used across all of your micro frontends then create a single store for single source of truth.
//add the code in componentdidmount where you want to receive the data
window.addEventListener("event-name", (datarecieved)=> {
console.log(datarecieved.detail);
}, false);
//Create an event to pass data
let send-data = new CustomEvent("event-name", {detail: "Hi Suraj here"});
window.dispatchEvent(send-data);
Pass data all across your mfes as when required in Home, Account, PLP&PDP and Cart&Checkout.
Up to my knowledge, Micro front end Architecture (MFeA) should not have any dependencies with other part of the page, it has to work independently.
Basing on that, backend service has to send the necessary information to the UI.
For user Information you can use Session and get the corresponding information from that.
For managing the User profile, it can be another MFeA module.
I've been looking into React.js. I was wondering if/when React.js relies on immutability for making decisions. I kinda get why it helps developers (elaboration in the context of React will be appreciated) but how does it help React itself?
How does it come into play for things like Virtual-DOM, shouldComponentUpdate, etc?
In my case, immutability is heavily used when I combine React with Redux. By using Redux, we create a data store which contained app state and will be shared across components. Redux encourage us to use pure function, which means there will be no mutation inside of it. For more explanation https://redux.js.org/faq/immutable-data#what-are-the-benefits-of-immutability
Context
Lately, during the development of a personal app there was a misunderstanding between the backend developer and myself. This misunderstanding led to a small change in the API for which the app was not prepared to handle (a field was removed from an object response data) and consequently led to crashes when the related component was mounted.
Possible solution
After that I realized that just by adding a model which could just provide the basic values that the app needs to work, just a basic class implementation of the request (let's say a book data i.e.), could have leveraged the impact of the issue.
Actual question
As I've seen few information about the topic I would like to ask the react / react native community if this approach is anti-pattern in some way or it is actually a valid solution.
You can just use propTypes or defaultProps to catch and handle this issue from the component level.
As far as in general having a client validate the response data from an API, I think the way you want to use it could be an anti-pattern in that a client should not be used to test/assert what that response data ought to be.
In your specific situation, perhaps a better solution is to maintain the test cases for the API. This will let you officially communicate to your backend developer what your expectations are, and avoid these problems in the future.
I am new to React.js and I am enjoying it a lot. I came across the Flux architecture while reading the React.js documentation. I understand that Flux is just a pattern and that there are many Flux implementations out there – including Facebook's own. I also know that React.js can be used without any Flux implementation.
My question is: is it safe to say that React.js has its own (small) Flux implementation embedded within it? In my opinion, I don't see any other way for React.js to achieve its uni-directional data-flow without having its own Flux implementation – which is, of course, replaceable with other Flux implementations.
Flux is pattern for handling application state and React is just view library. You don't have to use Flux with React, but it's preferred way.
Most popular Flux implementation seem to be Redux nowadays.
The picture below is an explanation of what is, and what is not in react:
The green stuff = part of React: a library to render a component tree in a DOM (or somewhere else).
Unidirectional flow means that react is made for/ allows only top-down updates: any component can render/ update/ change itself (through change in state) or its children (through passing props down the tree).
The blue parts are part of the Flux-pattern. React does not have any code/ library components for this.
The elements of flux make the circle complete: they allow react components to trigger actions, which in turn update stores, and can allow for (top) components to re-render based on changes in stores.
There are libraries (e.d. redux, reflux, alt) that implement the various elements of the flux architecture.
I'm very new to React, just experimenting with it. I'd like to know what are some common patterns, or libraries o built-ins for handling communication among components. For example, I have am input component and a "list" component that updates from the server according to what is in the input controller. Think of an autocomplete box. Since components have presentation logic, What if the two can't be "besides"? They're in different parts of the page and hence two different controllers.
Also, what if I have a login / logout button that works via Ajax? I imagine a lot of different components across the page reacting to the login / logout action reconfiguring themselves accord to a global "logged" state and the data retrieved from the server for the specific user that has logged in.
What is the best way that React "reacts" to those changes? Thanks
You should checkout Flux and Dispatcher.
It's kind of like a pub/sub system but without the problems of a pub/sub system. The advantage is that all events flow in one direction which makes the architecture much simpler and scalable.
If you haven't already, you should checkout Facebook's official React documentation. They have a really thorough tutorial that covers 90% of the scenarios you'll run into, including best practices for component interaction. They're also really good about building from no knowledge on up. Only takes about 20 minutes to go through: https://facebook.github.io/react/tutorial/tutorial.html
As mentioned in another answer, Redux is an amazing library for handling app state and keeping components separate that shouldn't know about each other. Basically, you can have parent and child components, but if you ever have a component with over 2 levels of children, you should consider using Redux (or Flux) to handle state between unrelated components. The problem redux solves is just breaking up those dependencies and still allowing components to have a single source of truth. Their official documentation is also really good: http://redux.js.org/