šŸŽ Checkout my Learn React by Making a Game course and get 1 month Free on Skillshare!

The useEffectEvent hook in React (ex useEvent)

Imagine that you have a child component nested in a parent component.

The child component executes an on-click handler received from the parent component.

Something like this:

const Parent = () => {
    const [messages, setMessages]Ā = useState([])
    const clickHandler = ()=> {
        // logic here
    }
    return <Child onClick={clickHandler} />
}

With this setup, if the Parent renders, then also the clickHandler function will be recalculated.

And this can could lead to a performance issue. If the Child also has many other sub-components all of them will be re-rendered.

We can try to use something like the useMemo() hook, but we are patching the problem instead of fixing the root cause.

Well, this is what the useEffectEvent() hook is made for. Using it, we can make some changes inside the clickHandler, and don't cause the re-render of the Child component, and therefore its subcomponents.

Initially, this hook was called useEvent(), but the React team renamed it to useEffectEvent(). The link to the renaming Github PR is here).

With the help of useEffectEvent(), once the function clickHandler is created, we can get access to the actual reference of the function.

const Parent = () => {
    const [messages, setMessages]Ā = useState([])
    /* add the useEffectEvent() hook to have
    constant reference to the function */
    const clickHandler = useEffectEvent(()=> {
        // logic here
        })
    return <Child onClick={clickHandler} />
}

Think of it as a more powerful useCallback() with no dependencies. I think it can be a game-changer when it comes to preventing child component re-rendering.

šŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.

šŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.


Leave a Reply

Your email address will not be published. Required fields are marked *