It's easy, just useState
in the parent and give the child a setter:
function Parent() {
const [api, setApi] = useState()
return <>
<button onClick={()=>api.doAlert()}>Trigger alert in child</button>
<Child setApi={setApi}/>
</>
}
function Child({setApi}) {
const [counter, setCounter] = useState(0)
const doAlert = () => alert("counter is " + counter)
useEffect(() => setApi({doAlert}), [counter])
return <button onClick={() => setCounter(c => c + 1)}>
Increment child counter
</button>
}
Top comments (0)