Where to store previous values in ReactJS - reactjs

I have a React component that represents a list of pages (used when paging through search results). For example, When I click on page 3, and then click a search result, a new page appears, and the component is destroyed. When I go back, it recreates the component, and the selected page is reset to 1. I want to keep the last selected page value, and default the selected page to that when the component is recreated. Where can I store a 'previouslySelectedPage' value, and how can I access it? (I'm a noob at React, do I have to store it in the state/props of a parent element that does not get destroyed when I click a search result, so that old values can be retained?)

One option is to store in the state of a parent that doesn't get unmounted and re-mounted. And then you can pass those state values as props to the child component.
The other option is to use something like redux to create data stores in your application. Adding redux to your app will not be a trivial undertaking but may provide some good value long term if your app is complex and will need to scale.

Related

After edit record in datatable, only first entry from backend is displayed using react

I have edit/delete functionality for records. when I come on actual page, it displays all data but when I actually edit/delete. Only first entry from cloudant is displayed. But if I again click on edit/delete functionality it displays all data. Must be issue with react state.
Adding details about my implementation.
state:
state in useEffect
I used Carbon components DataTable for rendering countryDetList data.
After edit/delete and Modal closing, only 1st record is displayed.
Becuase the state is not re-rendering
Check what are you setting in state
if you are using objects in state check how you are setting them
for example
const [User,SetUser] = React.useState({})
SetUser({id:21})
this might not be cause a re-render
SetUser({id:26})
you can make it like
SetUser({...{},...{id:26
}})

Relatively simple React app has a component re-rendering 7 times on page load

My React app is currently fairly simple in terms of structure, though the logic in the components is getting more intense. The structure is basically Index which has a Header component and, if the user is logged in, will load the Home component, which has components X, Y, and Z on it, corresponding to left sidebar, main area, and right sidebar.
As I'm working on the right sidebar, I have some console.log() statements to help out. I'm now noticing that the right sidebar Z component appears to render 7 times for a given fresh page load, based on how frequently I see my logging. This component has the rough following code:
Declaring various states for the component using React.useState([default value])
Checks the Redux store to fetch the currently authed user of my app (authedUser)
A React.useEffect() that checks if there is an authed user and if so, sets a couple component states. This useEffect triggers off of , [authedUser]); - I suspect this may be a cause of the rerendering?
Some click event handlers, including a more complex one that makes Google API calls when a certain button is clicked, using
The Redux store value for authedUser is used in Index, Header, and Z. The dispatch call that can change this store value only happens within functions relating to the user logging in.
Questions:
Am I right in being concerned that this component is re-rendering so much?
Any ideas on what might be causing it?
Are there any tools I can use to answer the "when/why is this re-rendering?" question?
You have a home component and three children's components on it. You may have a state variable in your home component and pass these state variables as props on to child components. Your home components re-render each time when each state variable changes its state, resulting in child components having to be re-rendered. So as to make the child component re-render only when its related state variable changes its state, you need to use the react memo and the useCallback hook.

Reactjs save current state of component

I have Component A and Component B. In component A, users can apply filters to a list of elements and they navigate between the two components using a side bar. Whenever users click to go to B, and back to A, the filters are set back to the initial state. What is the best way to save the state of component A so that when they come back to it, they see all of the filters they originally applied.
I Suggest you to use LocalStorage , pass in the filter so that it won't be reset. Upon mounting the component , you should always check first if does the localstorage have a value or not.
you can set it via :
localStorage.setItem('variableName', value);
and get it via :
localStorage.getItem('variableName');
It sounds like A is being created/destroyed every time you switch views, so it loses any state that it was storing.
Move the state up to a parent component of both A and B, and pass it down to A via props. The parent component won't be destroyed, so the state will persist.
Thinking in React may help clarify this.
In my knowledge; State in react is not cleared until it is programmed to do so, the page is refreshed or going to another page. Maybe it'll be more clear if you provide your code. One thing which I used to keep previous State is following:
this.setState((previousState) => ({ stateName: previousState.stateName.concat(newValue) }))
I think the parent state of A and B won't change unless you refresh the page.
Another way, you can use AsynStorage or store that data on the Server to retrieve it later when coming back to component A even you refresh the page.

React state updating unexpected

I'm trying to make a form with functionality where the user first views a list of days containing specific info about that day, can click a day, and then a unique form to edit info about that day appears as a modal. So the list is showing data from state, and the form shows that state as a defaultValue of inputs in the form. The form should have the functionality to save changes and to also cancel, which should close the form and forget any changes the user may have made.
The problem is that the form is displaying a value from state but when I press cancel, the changes I was in the middle of making still get sent to state, thereby updating the view of the list of days.
As a user I should expect to see the original data before I started editing, but what I'm seeing are the edits that I was making when I changed my mind.
here is a codeSandbox recreating the issue...
codeSandbox recreating issue
This seems like very basic functionality, but yet I can't seem to find any information on it. Am I missing some basic React concept here?
Props are passed by-ref in React. In your example, you're passing the days array all the way through to Form.js. On line 30 of Forms.js, you take the new value of the input field and store it in days[...].shifts[...].message, which changes the value in the original state object of the topmost component. Because this is done by mutating the state object and not by setState, the changes aren't seen until something else triggers a re-render of the topmost component, at which point the new values are shown in the button list.
One solution would be to store a temporary message state variable in the Form component and if the user clicks Submit, pass that current value back up as a parameter to this.props.onSubmit and let the top-level component use that value to update the days array properly (with a true state change as necessary).
Working example is here: https://codesandbox.io/s/9oqxlwol4o

How to manage state in react during react-router redirects

For example, say i have a child component (the row of a table) which has in its state a 'rating' key, with the value set to '0' in the constructor.
In getDerivedStateFromProps and ComponentDidMount, the rating is set to this.props.rating. so far so good.
Now the user sets a new rating, state is updated, the query to mysql is dispatched, and everything is good. But then the user clicks a Link (react-router-dom) to the same page they are already on. React updates all the components, but since the higher level component has not changed, it does not query the database again for the songs, and therefore the same set of songs is passed down as props, along with the old rating.
my question is simple: should the higher level component query the database each time the user redirects to the component? if so, is there a lifecycle method for this, since props aren't changing? or should the query for the new set of songs be sent each time the user selects a rating? the latter seems like the correct approach, but also inefficient.
You need to "lift your state up" so that it lives in the nearest common ancestor to all components that will need to access it. When you update your rating, you need to update the state in the higher level component, not the child component. The child component should be mostly presentational - it takes in a rating to display and provides a callback for updating it. But the actual updating and mySql interaction should happen at the higher ancestor level and get passed down through props.
Remember: the data flows down

Resources