Given two react components Parent and Child, we want to find a way to communicate from the child to the parent and viceversa. First one is pretty straight forward, we could simply pass an event handler/function from the parent to the child and let the child trigger it when needed.
function Child({ onAlert }) {
return (
<div onClick={onAlert} style="border: 1px dotted">
Click to alert the parent
</div>
);
}
function Parent() {
function handleChildAlert() {
alert("From child");
}
return <Child onAlert={handleChildAlert} />;
}
A way to handle the second one (triggering child event from parent component) is by using Refs:
const Child = forwardRef((props, ref) => {
useImperativeHandle(ref, () => ({
getAlert() {
alert("getAlert from Child");
}
}));
return <h1>Child</h1>;
});
function Parent() {
const childRef = useRef();
funciton handleClick() {
childRef.current.getAlert()
}
return (
<div>
<Child ref={childRef} />
<button onClick={handleClick}>Click to alert child</button>
</div>
);
}
But what if we need bi-directional communication between children and parent? And what if we also need to chain it, and even to be async?
This is exactly where we can use async/await props, and hopefully demonstrate some of its usability.
The next example is a very simple TODO app, with only two components. The first one “Todo” which has a text-input and a button to fetch one todo and finally to render it, the second one “App” has a function to fetch a todo by id from jsonplaceholder rest API.
By using async/await props we can not only achieve a smooth bi-directional component communication, but also we can create a generic react component/library to handle the business logic and let the final user provide her own API and data handling (mapping/reducing).