Changing children's state from another component with React Hooks

Pavel Laptev
ITNEXT
Published in
4 min readNov 17, 2019

--

Lately, I pretty often use React for rapid prototyping and developers' handoff, but I faced the problem when you need to change the state of the one component from another —in my case, it was a “Toast” component. Today let’s consider a few examples on this task.

Task

We have a CTA button in the parent component when we click on it we show a child component . Child component has a “close” button, when we click on it we hide the child component.

The main thing here is that we need to change the children’s state from the parent component — we should have only one sharable state. It would be easier if states and props were the same, because passing we can easily passing props in React but, unfortunately, no — states are dynamic and props are static.

Design and states

It's the basic toggle case with true and false statements.

Solution #1. Using Ref

In this example, we are using useRef, forwardRef and useImperativeHandle.

With useRef in the parent component, we can reach functions, props, and values inside the child component using useImperativeHandle.

For instance, we have this function in the child component and we need to reach it outside to show it:

when value is true we show the component, when false we hide it by toggling the className:

to do this we need to create useImperativeHandle and add showToast here

Then in the parent component, we can reach showToast function appealing to ref.current

Solution #2. Using Context Provider

In this case, we will share the same context for the child and for the parent component.

To do that we will need to create a new file ToastProvider.js and place our context there:

If we will google this approach, many cases will be dedicated to theme changing ThemeProvider like in this example — https://codesandbox.io/s/m5q79oq8y8?from-embed

And here is our solution:

That’s all, thank you :-) If you have your own solutions, please fork my examples and leave your solutions in the comments section below and I will add them to the article.

--

--