Home > OS >  how to go previous state without resetting state
how to go previous state without resetting state

Time:08-24

I have a problem. I have an example1.js file that fetches data from DB in options. when I select the option data shown in table form. when I click on the button to mark attendance it goes to another component e.g example2.js with param. but when I go back it must be in the same selected option. Anyone can help me. Code for go back is the following I am using.

import { useNavigate } from 'react-router-dom'; const navigate = useNavigate(); const goback=()=>{navigate(-1) };

CodePudding user response:

You can use redux or for going back you can simply use the in built js function of history i.e history.back()

CodePudding user response:

I highly recommend you to use Redux store for this: https://redux.js.org/

  1. Using Redux(recommended approach). You can create your own state and write reducer to handle/set/change state. In your component when you would like to receive the state you can use useSelector hook or connect, if want to change your state, use useDispatch, please read how to create a store and usage of hooks related to Redux: https://react-redux.js.org/api/hooks

  2. Using context(not recommended for your purposes because it is not designed for high-performance/many actions. But it is easier to setup/use if you don't need a Redux). Please read about context: https://reactjs.org/docs/context.html

All in all, you need to preserve your state 'somewhere' in Redux or Context to prevent refreshing the data while navigating/rerendering the component.

CodePudding user response:

I you are not comfortable to use redux then try to use react reducers and context api together to create redux like structure. It helps maintaining states between different routes even on navigation. You can refer these link.

https://hmh.engineering/using-react-contextapi-usereducer-as-a-replacement-of-redux-as-a-state-management-architecture-336452b2930e

https://blog.logrocket.com/react-hooks-context-redux-state-management/

  • Related