DEV Community

Luke Miles
Luke Miles

Posted on

3 1

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)

nextjs tutorial video

Youtube Tutorial Series πŸ“Ί

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series πŸ‘€

Watch the Youtube series