React passing state between instances of the same Component - reactjs

I'm fairly new to React, and I was trying to create an app that functioned thusly:
The app consists of several Pages, with multiple Components on each Page.
One of these Components is stats, which can change as the user interacts with Components on the Page.
When a user clicks on a certain Component, they will be taken to a "different" page, which is really just another Page, with different text, data, etc. This is carried out through the browserHistory.push() method. I would like to be able to carry over the changed 'stats' component from one Page to the next, but I am not sure how to do so. Furthermore, since I set the default value for stats in the Page component, it seems that any attempt at passing the changed values into the new Page would result in the new values being overridden. Can anyone help me?
Thanks.

State should live above the level of all components that need access to that state.
Remember that one of the principles of React is "one-way" data flow down the component hierarchy. Essentially, data/state should live at a high level, getting passed down to child components and consumed as needed.
In your case, you have some "stats" data that needs to be displayed across multiple Pages. So, "stats" needs to be owned by a component above all of your Page components - perhaps at the root component of the app itself. Pages themselves would just take the data in and render it, potentially with some callbacks appropriate for editing the data.
Read a bit more about Facebook's philosophy for React in "Thinking in React" in the official docs: https://facebook.github.io/react/docs/thinking-in-react.html#step-4-identify-where-your-state-should-live

One option to consider is to use React Redux to store the state of your application. You would then use mapStateToProps (See Redux API for details) to map the state into props for your stats component.

Related

When I store data in Redux and when not?

I'm working with a react app and currently working with a feature. The main task is showing some charts by getting data from API. And these charts will show the last 30 minutes' data.
I have questions,
In this situation, is it necessary to store these data in the state by Redux, though it can be handled at components very easily? And every time I refresh or request, I get new data (log base data).
When do we make the mind to store data in state and when not?
A redux store is a singleton, thus a single source of truth that can be made available to all components in the whole react application. If your state is intended only for one react component then you don't need a redux store. A useReducer react hook allows to well reproduce the redux pattern in a single component. Stick with a useReducer hook for a single component and use redux library for a store available to an app composed of several components.
Redux is not designed for the specif role of a special type of data.
You can use still store your temporary (30 min) data into redux, and use it to cross your feeling the same as the rest of your data.
But in this case, you might need to reset data after 30 minutes or invalidate your cache, keep your eye in react-query and RTK-query handling these types of actions more easily for you.
If data is being used for many states or those data are being used by many components then you should use redux. You can still go without redux, it is up to you after all.
If you have various components and routes then redux will help you to reduce the codes and also make the codes simpler.
Redux will give the one store for all the components in the project to store and access the data which is better then context or props tricks.
Also if you want to achive something like if user opened two different tabs. Let it be same page or two different pages of your website and if user done an action on page A and you want that page A or page B opened in another tab should get that update then redux can let you achieve that. Context and props passing are not useful in this case.
https://redux.js.org/faq/general#when-should-i-use-redux
Redux is most useful when in cases when:
You have large amounts of application state that are needed in many places in the app
The app state is updated frequently
The logic to update that state may be complex
The app has a medium or large-sized codebase, and might be worked on by many people
You need to see how that state is being updated over time

How to store input's values between Routed pages with tab

I have a react application which will contains dozens of screen for admin panel. I decided to open pages in tabs that integrated to react-router. When i change the current page and return back same page everything entered on inputs are being disappeared.
What is the best practice for this problem. It should be scaleable and must not require to write code in every page developed by a developer.
Also I use Redux for transferring userContext and appContext to every screen. Is Redux usable to store every input or other components' values?
It's possible to create store for keeping input valus. You may update does valus on input changes and check if the store object has value on componentDidMount you can import values from store to inputs.
React state is good for storing data inside a component and even to pass it to its children. It is not ideal for passing data among siblings. This is the exact case you have described above with dozens of components that do not share parent-child relationship.
The ideal solution for this problem is Redux. When you application state is stored in Redux, you can easily switch pages and not loose any data. Moreover, you can store the same Redux state in localStorage to prevent data loss due to browser refresh or shutdown. Lastly, if a need arises to persist your data in a database, fetch all the store values into props with mapStateToProps and pass them to backend.

SPA + back button + form state

I am converting a jsp multi-page app(mpa) into a React single-page app (spa). In the mpa, the back button worked and the form retained its state.
In my new React app, the back button works but the form does not retain its state.
Question: is there a trick to make my form retain its state after "backing" to it (in an spa).
Here are the two solutions I came up with:
Encode the entire form state into the url. Then update the browser history with an updated url every time the form changes. But, this seems like a huge pain in the butt.
Modify the structure of my app such that the form in question (a React Component) stays mounted (and just use the css visibility or display property to show and hide). But, in a large app, leaving every page mounted in the DOM seems like it might lead to performance problems.
By the way, I am using popstate and the browser history api to achieve SPA behavior (i.e. i have rolled my own router) as described here.
Hopefully someone can propose a solution that is better than my two solutions. Thanks.
I ended up using something similar to Wylie Кулик's answer with a few changes:
I didn't want to switch to Redux for just this one use-case. So I used the component state of my top-level component (i.e. a component higher up the tree).
I cached the form's state on the form component's componentWillUnmount and restored the cached state on componentDidMount.
I passed the cached state as a prop from the higher component to the child component.
It ended up being a very small amount of code and is working like a charm so far.
Use Redux to have a state store which transcends any particular component. Then in your component, as part of the form submission process, dispatch an action with payload of all of the form data. This should be cached on state and then when the component is remounted by your navigation structure, it should have access to this cache via Reduxsconnectfunctions mapStateToProps method. You can repopulate your form from that.
It's not clear from your question whether or not you are submitting the form in the traditional old way. I would use e.preventDefault in the handler instead, and have all the form data on the component's state, this can be sent to Redux's state store as described above, and Ajaxed off with superagent or similar. At the same time it can be cached.
Redux: http://redux.js.org

What to store in redux state?

I'm building a medium-sized React/Redux app, and I've become very comfortable with React - however, Redux is still a little hard to wrap my head around.
I understand that I can use connect() from Redux to connect any Component or Container to Redux state. However, I'm unclear on when to do this - is it based on complexity? How many props would need to be passed down to child components?
What are the factors I can use to determine when to use connect()?
Edit to provide an example: -----
For example, I'd like to include a messages area for users inside my app, particularly a badge showing number of unread messages. Would I simply connect() any component where I'd like to display the badge?
I DON'T agree about storing all component state in the store. I prefer having in the redux store only data that matters to application as a whole and thus other components may benefit from this global accessible shared data.
Having component specific state in the store, that only matters to this component, is a overkill and useless IMO.
You store the state of your app in redux. How you structure your state tree is up to you. You can think of the state tree as one giant javascript object. With redux, you would ideally store as little component state in your react components themselves and instead move that to the redux state tree.
For example, if you fetched some user data, you could store that in the redux state such that your connected components have access to that data now. You can also get more granular and store states that describe certain UI components. A part of your state that describes a dropdown could look like this
{
myDropdown: {
isOpen: false,
options: [
'apple',
'orange'
]
}
}
I believe a good point to start incorporating redux is when your app gets to a certain point where your components are no longer just "dumb" components that display data.
Edit:
To try and answer the question "when should I connect my components?". I struggled with this myself but don't have a great answer yet. Right now I typically connect a component if I am passing down props through many ancestor components just for that component specifically. So connecting would avoid that boilerplate code altogether.
Official REDUX page:
https://redux.js.org/faq/organizing-state#do-i-have-to-put-all-my-state-into-redux-should-i-ever-use-reacts-setstate
Some common rules of thumb for determining what kind of data should be put into Redux:
Do other parts of the application care about this data?
Do you need to be able to create further derived data based on this original data?
Is the same data being used to drive multiple components?
Is there value to you in being able to restore this state to a given point in time
Do you want to cache the data
List item
But...that means in most of off applications the only data what I should store in Redux store is the logged in user data. That is the only entity which attributes influences all the screens (role, login name, user settings).
Usual applications do not need to remember entered data between screens, cache, history....
Very confusing, so I am not really sure any more what to put in Redux store...

React && Flux confused about where to put data

I'm developing a web app with React + Flux. But sometimes, I am confused about where to put the data of a component.
Flux says that we should keep the data in the store. When the data changed, store should emit a change event, then the react components which listen to the store's change event should call setState with the data in the store.
But in this way, one react component is made by two parts, which are the component it self, and the store to be listened. Sometimes I want the component to be more individual. I don't want some state of this component to be related to any store, so I store the state in the component jsx file. In this way it is not a flux style, but just react.
I'm not sure if I'm doing the right thing. Should a fluxible app to be totally obey the flux or not?
There is no right answer to this question.
You could differentiate between application state and view state just as much as you could reason that all state should live in one global store.
Application state could be User information, product information or that type of data whereas view state could be related to toggling a div or what color a link should have depending on the application state.
These two approaches are both used in the wild and there is just a matter of preference.
This is a good read that argues for the case of a single state.
I won't link to the other reasoning as it's the "flux way" and an easy Google

Resources