Slowly implementing redux to an existing React.js project - reactjs

I want to migrate my project from plain react to react redux, I am not new to React but new to Redux.
I have a fairly big web app written in React, dozens of React.js files.
most of them containing state's + passing variables between them.
including allot of Post/Get requests functions, implemented into at least half of my files.
I want to slowly move from plain react to react redux.
I wanted to ask if anyone have some article or can give an insight about migrating existing react project to react-redux.
I dont want to stop development for the sole purpose of the change but instead to slowly adapt to it.
is it possible ? is there a tool to help me do it ?
I saw some redux examples where entire render of app.js was surrounded by <Provider> </Provider>, does that mean every component inside <Provider> bracelet can not have it's own state ?
can I simply keep my old components as they are and put new ones into <Provider> </Provider> ?
Thanks in advance!

I saw some redux examples where entire render of app.js was surrounded
by , does that mean every component inside
bracelet can not have it's own state ?
The way react-redux works is by exposing a store prop, provided by the Provider. In order to consume it, or extract data from it you must wrap your component by it (not directly necessarily, but one of the parents must be a provider). In general in most apps you would simply wrap the entire application with a Provider, because for the most part, if you've chosen to introduce redux into your application, it is probably because your entire app needs some store.
Using redux does not mean that components can't have state. There is a big difference between global state - something that should be accessible to every component in your app (if the component chooses to "consume" it), and state that is private to a component - e.g. form changes before being sent to the server.
can I simply keep my old components as they are and put new ones into ?
Well, yes. But also - no. As I said earlier, you should probably start from the top and slowly drill down. Wrap your app with a Provider, and start moving your application state from the top-most component to the store. Once you get more comfortable with redux in general, you should start replacing the props you pass down the component tree with props from the state by connecting your inner components.
This way you can do it one component at a time without breaking existing logic.

Related

What's the difference between React App and React Component

We will be doing our first project using React.
It will not be a Single Page App, but a Multiple Page App.
What I'm trying to figure out at the moment is : what's the difference between a component and an app.
If I only use components, can I still use Redux to have some state management on the current page ? Or do I need an app for this ?
Thanks for the information you can bring !
THoma
There is no special object called "React App". React Components build an "React App" by coming together.
But React Components are formed like tree structure. That means each component have a parent component so you can create a React Component that named "App" and can put another components inside it.
You don't need redux for state management in React Components.
I hope the answers have helped.
Your app may contains a single component and still it will be a react App. If you are using multiple components in a page you can still use react-redux. Redux is basically a container for your states and let suppose you need some state from one component to be consumed in another, Redux provide you a mechanism to make the communication efficient and predictable.
You can also look at the React Context APIs as an alternate to Redux.
An app is simply a component that holds the root of the work you are trying to do. For example an App may have the navigation menu, testimonials, adverts, content, login avitar etc.
If you are making a single App per page (For example a testimonial) then you would still have a SPA. For example, adding testimonials, searching, editing.
You should only use Redux if you are using a SPA with lots of different parts with data in common. If you are making a one-app-per-page and there is no cross over in data then you can simply using Reacts State/Props to hold your data.
Redux is good, but it forces you into a complex path your should try to avoid. If you find yourself wanting data from different domains (customers address and a list of testimonials) then you should use Redux.
If this is a new applications (green) then I strongly recommend you build the whole thing within a SPA using React-Router to control components. you can use frameworks like Next.JS to ensure the site remains small in size (dynamically loading script only when required).

React components with shared state that are far away

I am new to React so please excuse me if this is a noob question but I really could not find the answer in the DOCs or elsewhere.
Let's say I have two buttons with a counter that share the state but are far away from each other in terms of the placement in the UI.
The documentation says the common owner component for both buttons should own the state. It makes sense if the components are next to each other like in the example but what if my buttons are each part of a different UI group and are far away in terms of nesting? My state holder would be the root of the document and I would have to pass a handler function down through many layers. And what if I need to add new component somewhere else that also needs to know the state? Would I have to modify all the parent components in the way to pass the state down? That is tremendously impractical.
Without React I would have some global Subscribe/Publish pattern like jQuery Observer and all UI elements could subscribe/publish to it regardless of their nesting position.
How does React solve this?
Related question: If I need to load/save the state to DB, how do I pass a reference of the controller (or Whatever) to each React component that stores the state?
1 for global state you may use REDUX
Redux is a predictable state container for JavaScript apps
for connect/subscribe component with that state ,you should use react-redux
If components are far away in terms of nesting, you may connect/subscribe them to redux store, and take only neccessary part of state. They will update if only neccessary part is changed.
article that explains how you can do your case
to learn how to use redux you can watch this videos from creator of redux (Dan Abramov)
1.getting-started-with-redux
2.building-react-applications-with-idiomatic-redux
3.I definitely recommend to you discordapp rectiflux channel. because you allways can ask any question online.(there you can find contributors of that tools)
2 alternative way that less verbose then redux is MobX
MobX is a battle tested library that makes state management simple and scalable by transparently applying functional reactive programming (TFRP). The philosophy behind MobX is very simple:
Anything that can be derived from the application state, should be derived. Automatically.
I suggest to look at the Flux stores. In short, stores are like model in your application. You can listen to change (subscribe) and also modify their properties (publish). You can see how it was done in example app.
A better option is to go with Redux.
Redux is enabling use cases like yours in a way simpler fashion :)
It will help you with all the state and make your life much easier.
Some good resources for learning:
The Redux Website
Video courses from Dan Abramov, the creator [Free]
Awesome course on Udemy [Not free]
Building Applications with React and Redux in ES6
And finally take a look at this youtube series [Free]
Managing state in the middle layers of your app should be avoided where possible. This data belongs in a store, which holds the global state of the app. Then each component accesses the state via its props.
The naïve approach to get the data down to the component is to pass the store through all the layers of your app "manually", i.e. through props.
Smarter alternatives exist, which use connected components, that access the global state through the context (as opposed to the props). Typically, the presentational component (your button component) is wrapped in a container component that handles this connection to the store, then passes the data in via props.
There are numerous frameworks that facilitate this process, links to which are already provided in the other answers.
If you are trying to share simple states, try this ( I am the author): react-provide-state
Otherwise I will recommend Redux. It has become the most popular tool for managing application states.
In the applications being working on, we use Redux to manage the main application states and almost all other states. But we use 'react-provide-state' for simple, UI only states like Modal, Checkbox states.

Passing down props in a React library invisible to the app using the library

I am developing an open source library to use the Ionic framework with React (it normally works with Angular): https://github.com/pors/reactionic/
This React-Ionic library can be used by developers to create mobile apps. These apps will have their own way to keep state in their app, either by passing down props through composition, or using Flux/Redux, etc.
The React-Ionic library also needs to keep state for a number of things. For example, the "Body" component that wraps all contents needs to know if the content contains "Tabs". So the "Tabs" component needs to be able to change the state in a higher-up component.
I currently use composition to do this, but this has the disadvantage that the app developer needs to pass on props that are specific to the React-Ionic library. I want these props to be invisible for the developer.
What is the "React way" of solving this? I can think of two things, please let me know what the best solution is:
Use context.
Use Flex/Redux just for the library. Is this possible? Won't it interfere with the "state management" used by the app?
Otherwise?
I have added an image that hopefully clarifies what I try to accomplish:
So I want to pass state information down from the IonBody component to the IonTabs component, without the "App component" having to pass props down. And similarly, the IonTabs component should be able to call an IonBody function.
Thanks!
1) If you want to pass props down so they "fall through" to a child component, you can use the JSX spread operator, which will merge in old props:
<Component {...this.props} more="values" />
2) Context is an experimental feature and shouldn't be used unless in a very specific few cases; it essentially lets you create a "falling leaf" outside the state tree you create w/ props. This can lead to very unexpected results since it is generally outside the React/Flux paradigms. There are a few use cases for it, but they're generally only as last-resorts or only with very specific rationale
3) With one-way data flow, you generally want to use something like Flux/Redux for your state management. Child components don't get to really know about their parents, and vice versa. They communicate via props (and only top-down, really), so actions need to go "back to the top" of the state tree and propagate down from there.
As a last note, I wonder if you might consider React-native over React-ionic. It's going places IMO and is probably the ideal choice for taking a React app native. Just a thought :)

What is the use of Redux-Router in addition to reac-router?

guys. When I go through the documentation of redux-router, I just cannot understand why do we need it?
Here is what the documentation is trying to explain:
React Router is a fantastic routing library, but one downside is that
it abstracts away a very crucial piece of application state — the
current route! This abstraction is super useful for route matching and
rendering, but the API for interacting with the router to 1) trigger
transitions and 2) react to state changes within the component
lifecycle leaves something to be desired.
It turns out we already solved these problems with Flux (and Redux):
We use action creators to trigger state changes, and we use
higher-order components to subscribe to state changes.
This library allows you to keep your router state inside your Redux
store. So getting the current pathname, query, and params is as easy
as selecting any other part of your application state.
As far as I can understand, it is trying to say redux router can keep router state inside redux store so that we can get route info more conveniently.
But within react-router, I can also easily do it.
Like path="messages/:id", I can use this.props.params.id to get the params.
Can someone explain in what scenario redux-router bring its benefit?
Redux (and in general, the flux pattern) is all about having the entire application state stored in one central place. This has the benefit of easier debugging and makes it easier to implement certain features.
If you've ever used the redux-devtools in a react app with react-router, you'll notice that its only of limited use, because you can't replay the entire lifecycle of the application. When the user changes routes, that's not recorded in the redux store. Redux Router keeps the route state in the store.
You could use this for debugging, you could serialise the entire store history and log it elsewhere to replay user sessions. You could hook into it to implement full undo, or log analytics events.
redux-simple-router is a library which could help you understand how to use react router in a redux application.
It is a very simple library stores the URL in redux state and keeps it in sync with any react-router changes.
redux-simple-router compared to redux-router is:
Much smaller and simpler. You don't need to learn another library on top of everything else.
Encourages direct access of react-router APIs. Need server-side rendering, or something else advanced? Just read react-router's docs.
Only stores the current URL and state, whereas redux-router stores the entire location object from react-router.
Follow one of the these 2 examples to get up and running:
redux-simple-router-example
redux-frontend-boilerplate

Issue with UI event when rendering component inside a web component shadow DOM

I'm facing some issues when rendering a React component into the shadow DOM of a webcomponent.
I wrote a small piece of code to turn a React component into a webcomponent, but I want to render the
React component inside the shadow DOM of the webcomponent. But in that case, it seems that React is not able to catch UI events (click, keyPress, etc ...) anymore.
Let's take an example, let say that I have a first webcomponent <awesome-timer /> that render the React component inside the webcomponent node, and another webcomponent <less-awesome-timer /> that render the React component inside the shadow DOM of the webcomponent.
Both webcomponents use the same React component. However the one rendered inside the shadow DOM does not work, because click events on the button of the timer component does not trigger the bound function.
I guess React is not designed to handle such case, but I'd love to get more details about it.
The code of the example is available here : https://gist.github.com/mathieuancelin/cca14d31184bf4468bc1
Does anyone have an idea about it ?
I know this is kinda late but, I believe your issue when you pass any attributes to a web component they instantly become strings Because that's all you can pass to a web component. Now of course you can convert or cast them back to there original data type, except functions because once stringified they loose there scoping, lexical and all.
Now to your main question, you are were trying to pass you child element through the Main web components slot. Now you have to remember that once you pass anything to a web component you now have to use the webs components methods and return types to manage whatever you pass. So yes passing react into a web component will not work they you expect.
You will need to go back to whatever tool you use to build your web component and deal with the slot logic there. Since this is a very old post as are web components. You might not have had access to the modern web component build tool's we have today. I found Stenicl allows you to build and manage your web components in Typescript.
A good option is to change your pattern a little bit and just return web components from your react app.
Or you can use another really cool to call Lit-HTML or Lit-element. I believe they may have combined there core libraries. Anyway these tool will allow you to combine Reactjs and web components where lit-html gives you access to methods simial to Reactjs's life cycle methods. Anyway some good stuff to check out if your stuck at this point.

Resources