Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

The best way to store multiple components' state for children in React within a single context is to use the useState hook and the useContext hook.

First, create a new context using createContext:

const MyContext = React.createContext();

Then, create a state object to store the state of all the components:

const [state, setState] = useState({})

Next, create a custom provider component that updates the state and passes it down to its children using the context provider:

function MyProvider(props) {
  const [state, setState] = useState({})

  const updateState = (key, value) => {
    setState(prevState => ({ ...prevState, [key]: value }))
  }

  return (
    <MyContext.Provider value={{ state, updateState }}>
      {props.children}
    </MyContext.Provider>
  )
}

Finally, use the useContext hook in the child components to access the state and the updateState function:

function MyChildComponent() {
  const { state, updateState } = useContext(MyContext)

  const handleClick = () => {
    updateState('key', 'value')
  }

  return (
    <div>
      {state.key}
      <button onClick={handleClick}>Update</button>
    </div>
  )
}

This way, all the child components can access and update the shared state stored in the context.