Most efficient way to pass parameters in onClick handler

后端 未结 4 408
生来不讨喜
生来不讨喜 2021-01-02 04:09

I am using inline arrow function to change the onClick handlers of some divs in my React component, but I know it is not a good way in terms of performance.

4条回答
  •  暖寄归人
    2021-01-02 04:20

    The best way currently is to wrap your event handler in useCallback hook as it will prevent your handler function from being created each time render is called.

    import React, { useCallback } from 'react'
    
    const MyComponent = ({ changeRoute }) => {
      const eventHandler = useCallback(() => {
        changeRoute('page1')
      }, [changeRoute])
    
      return (
        
    1
    ) }

    For more info check - useCallback docs

提交回复
热议问题