Ask Your Question
0

What is the best way to store multiple components' state for children in React within a single context?

asked 2023-05-29 15:22:19 +0000

lalupa gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2023-05-29 15:33:02 +0000

scrum gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-05-29 15:22:19 +0000

Seen: 9 times

Last updated: May 29 '23