• Native events are events at the browser level
  • Custom events are a mechanism implemented purely by components

First, do all callbacks need to be wrapped in useCallback?

– The need to use useCallback is not necessarily related to function complexity, but rather to which component the callback function is bound to. This is to avoid unnecessary rerendering due to changes in component properties.

With native DOM nodes such as Button, Input, etc., we don’t have to worry about rerendering. So, if the event handler is passed to the native node, then the callback may not be written.

But if you are using a custom component, or some UI framework component, then the callbacks should be wrapped in useCallback.

  • How events are handled in React (the browser’s bubble model)

    • Due to the existence of virtual DOM, even if an event is bound to the native DOM node in React, the event is not bound to the corresponding node, but all events are bound to the root node. React then monitors and manages events and distributes them to specific DOM nodes
    • Prior to React17, all events were bound to the Document; After React17, all events are bound to the root node of the entire App, mainly for the consideration that there may be multiple versions of React on the page in the future

    React does this for two main reasons:

    1. When the virtual DOM is rendered, it is possible that there is no real render on the page, and then the event cannot be bound to the node
    2. React can block the details of the underlying events to avoid browser compatibility issues. This provides a consistent API that supports the way events were previously defined on the native DOM
  • Create a custom event

    • The essence is the component’s own behavior, a function callback

    • Native events are the browser mechanism

    Example, encapsulate keyboard events with Hooks

-Hook Has the ability to bind any data source

import { useEffect, useState } from 'react'

const useKeyPress = (domNode = document.body) = > {

    const [key,setKey] = useState(null)

    useEffect(() = > {

        const handlePress = (evt) = > {

            setKey(evt.keyCode)

        }

        domNode.addEventListener('keyPress', handlePress)

        return () = > {

            domNode.removeEventListener('keyPress',handlePress)

        }

    }, [domNode])

    return key

}
Copy the code

Use:

function useKeyPressExample() {

    // Use custom hooks

    const key = useKeyPress()

    return (

        <div>

            <h1>Please key press</h1>

            <label>Key pressed: {key || "N/A"}</label>

        </div>)}Copy the code