Jsx props should not use arrow functions

In JSX, it is generally recommended not to use arrow functions for props. Let’s understand why and how to avoid using arrow functions as props in React components.

Arrow functions create a new function instance every time a component renders. This can lead to unnecessary re-rendering of child components, impacting performance. To optimize rendering, it is advised to define functions outside the component and pass them as props instead of using arrow functions inline.

Here’s an example to illustrate this:

    
      // Incorrect way: Using arrow function as prop
      
      const ParentComponent = () => {
        const handleClick = () => {
          console.log("Button clicked");
        };

        return (
          <ChildComponent handleClick={() => handleClick()} />
        );
      };

      // Correct way: Passing function as prop

      const ParentComponent = () => {
        const handleClick = () => {
          console.log("Button clicked");
        };

        return (
          <ChildComponent handleClick={handleClick} />
        );
      };
    
  

In the incorrect example, an arrow function is used as the prop for the handleClick event. This creates a new function instance every time ParentComponent is rendered. As a result, ChildComponent may unnecessarily re-render, even if the props passed to it remain the same.

In the correct example, the handleClick function is defined outside the component and passed as a prop. This ensures that the same function instance is used for each render, optimizing performance and preventing unnecessary re-renders in ChildComponent.

Similar post

Leave a comment