DEV Community

Luke Harold Miles
Luke Harold Miles

Posted on

How to pass functions from child component to parent in React without useRef or useImperativeHandle

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>
}
Enter fullscreen mode Exit fullscreen mode

Demo: https://jscomplete.com/playground/s732915

Top comments (0)