Search code examples
reactjsreact-propsreact-state-management

What are the ways of maintaining state of an object throughout the react js pages


so in our project the data will be entered on the 1st page component and we want that data on the 5th page not on the 2nd 3rd 4th page. we are not able to maintain the state of object till the 5th page


Solution

  • You can use a Context item.

    You can create an object which can be accesible in multiple components. This can, of course, be combined with state.

    1-Create the context (in this case I made a component wrapper to make it easier to include in the code.

    export const DataContext= React.createContext({
      data: 60, //Default values in case no value is provided
      setData: () => {}
    });
    
    export function DataContextContainer({children}) {
      const [data, setData] = useState(60);
    
      return (
        <DataContext.Provider value={{ data, setData}}>
          {children}
        </DataContext.Provider>
      );
    }
    

    2-Wrap your desired components (which will read that data) with the component

    import {DataContextContainer} from "./DataContextContainer";
     ...
    <DataContextContainer>
        ...
             <YourComponent/>
        ...
    </DataContextContainer>
    

    3- Now you can easily have access to that object in any of the components wrapped using the hook useContext or a context consumer.

    import {DataContext} from './DataContext'
    
    ...
        const {data, setData} = useContext(DataContext);
    ...
    

    4- Use it in your input:

    <input type="text" value={data} onChange={(e) => setData(e.target.value)}/>