How to trigger sibling component function from another sibling component in React?

353 views Asked by At

In React I have a parent component with three sibling components, e.g.:

<div>
   <Component1/>
   <Component2/>
   <Buttons/>
</div>

I want to trigger functions defined in <Component1/> and <Component2/> from the <Buttons/> component. Currently I am using useImperativeHandle with forwardRef to export the functions from <Component1/> and <Component2/> and passing them to the <Buttons/> component via its props.

It works, but it doesn't seem the best way. What would be the recommended React pattern of doing this if I don't want to move <Component1/> and <Component2/> functions and state handling to the parent component?

1

There are 1 answers

1
Slim On

I would have suggested moving the state to the parent but since you prefer not to, you can use context with hooks

Creating the Context

export const AppContext = React.createContext();

Using it where needed (import the context and useContext prior)

const {state, dispatch} = useContext(AppContext);

Official doc: https://reactjs.org/docs/hooks-reference.html#usecontext