best practices for keep states of page in react-router application - reactjs

I Have react app which contains many pages. For each page i added store. I using params from url for example photoId then passing to actioncreator which call service and then dispatching data to store. In page component i have store listener. Store imiting change and listener calling render for new state.
Store and action creator relates to this page only. How to create pages more simple?
Thank you!

The Flux model (using actions, dispatcher, and stores) works well for larger apps where a data fetch may affect many components and pages. If you think your app will grow then it may be worth the extra verbosity. If you're keeping your app small then composing plain React components is a great way to keep things simple and there is nothing wrong with doing it as long as you separate the data operations from the display, the way your linked example showed. Have fun!

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

About calling API in reactjs

I have a question about calling API in react.
Example in the website. We have a lot of page. Each page has a lot of components. And each component has its own data need to get in server.
I see we have two way to call API is:
First. We call all API of each page in a root of each page then set the data to state. After that, we pass data to children Component.
Second. In each component, we call its API to get its data then set the data to component 's state.
So which is better. I need an explain about that.
Thanks you,
There are many ways to pass Data through out the components.
If the application is small and there are small number of child components you can go by making calls in Root folder.
There would be some components that always doesn't render and only rendered based on specific conditions at this point you can go by making calls from that component.
Using redux and redux thunk is always an option if the data is needed in many components and data can be accessed at any point of time.
As noted in the previous answers/comments you could do either one of these. If you plan to use redux it might be easier to chain the api calls in a single action w/ thunk that gets ran on main component load.
Context or Redux would do you well so you don't have to pass tons of data through prop levels.(prop drilling)
I would suggest Redux, IMO context gets too cluttered and by the time you've properly atomized your code to clean up everything you may as well have just went through the overhead of adding redux.
What you should ask yourself is-
Does it make sense to have all this data load at the same time?
Is it appropriate for some api calls to be made from the components that will use them?
You have creative license to do what works best for you.

React passing state between instances of the same Component

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.

Simple data fetch in Flux design pattern

Flux design pattern has been such help in simplifying my web application. However I ended up directly calling web APIs for certain situations simply because Flux seemed such overkill for the job. I was wondering how others might have solved such problem in a Flux way.
As the diagram suggests, we created the Action via the Action Creator for all Web API calls. I will give an example scenario. Let's say there are 3 components that are interested in User Store changes at the moment. User clicks one of them to load a list of user's hobbies from the back-end. But I only want only that one particular UI component to display the list of hobbies due to the user's action. The other 2 components won't change at all. Traditionally this would have been a simple couple lines asynch call with a callback. If you are to religiously follow Flux for this,
You create an action via Action Creator with a specific reference ID
Fetch data via Web API
Upon receiving data, action is created using the Action Creator
User store listens to this result arriving via the action
Update the store
Fire store updated event, all 3 components react to that and check if that was for mine using the reference ID
then finally render with the data fetched in that 1 UI component
My app having many small parts that load data dynamically like this per user action, I decided to use Flux for things that many components have to share states with since the stores act as centralized state provider. How do you guys use Flux to do simple data fetches such as the one mentioned above?
There are couple of ways to solve this.
Let all the components receive the update and the component decide whether to update or ignore the update.
Split up your store and subscribe only to those which are need in the component. This approach can get messy with stores getting dependent on each other and simultaneous dispatch problem.
If you haven't used any flux library , redux is highly recommended. It solves this by allowing the components to subscribe to part of state(store) tree.

Handle datagrid pagination with React/Redux

I'm working on a React + Redux application, and I need to display a datagrid with paginated data. I have potentially thousands of rows, but I don't want virtual loading through scrollbar; I want pagination. I load data through Ajax calls.
I'm probably going to use jqGrid which seems to be a fine candidate for the job, as it can load data given on the fly, and display a "virtual" pager for data which is not yet loaded.
My question is about how I handle that in the React + Redux world.
Should I make Ajax calls in action creators, and pass the fetched data to reducers, to put it in the state, so then components which are subscribed to the Redux store can get it?
Or should I make the Ajax calls directly in the component?
Also where should I keep the querying data (page number, items count per page, total number of rows, sorting/grouping/filtering informations)? In the component or in the state?
Keeping the ajax logic in async action creators (with redux-thunk middleware) is generally a cleaner solution than messing with ajax inside components. Ideally your components should be dumb, only dealing with the props they're fed. If you're not familiar with async action creators in Redux, the docs cover it quite well: http://redux.js.org/docs/advanced/AsyncActions.html
As for storing stuff in the Redux store vs. components, the general rule of thumb is that if you want to replay a certain state, or the state says something about the application as a whole: keep it in Redux. With Redux I only use component state for trivial stuff like displaying tooltips, and other things that don't have much to do with the general data model. Of course, React and Redux don't force you to do it in one way or another, but speaking from experience, using the Redux ecosystem to handle flow of data and metadata in an application makes it much easier to reason about the code later, especially when using redux-devtools.

Resources