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)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay