Skip to main content

2 posts tagged with "re-render"

View All Tags

Reasons to Avoid Nested Components

· 4 min read
Hyunmo Ahn
Front End Engineer @ Line+

Introduction

During a project, I encountered an issue where unnecessary re-renders were occurring.

The problem was not just rendering, but the fact that the DOM was being completely redrawn with each render. The culprit was the use of nested components in the code.

In this article, I will explain why you should avoid using nested components.

Cheat Sheet

// Bad
const List = ({ hasWrapper, borderStyle, children }) => {
const Border = () => {
return <p style={borderStyle}>{children}</p>;
}

if (hasWrapper) {
return (
<Wrapper>
<Border />
</Wrapper>
);
}

return <Border/>;
};
// Good
const List = ({ hasWrapper, borderStyle, children }) => {
if (hasWrapper) {
return (
<Wrapper>
<Border borderStyle={borderStyle}>
{children}
</Border>
</Wrapper>
);
}

return (
<Border borderStyle={borderStyle}>
{children}
</Border>
);
};

const Border = ({ borderStyle, children }) => {
return <p style={borderStyle}>{children}</p>;
}

As shown above, you might use a nested component to reuse the code for Border and the props of List. However, in such cases, the children are unnecessarily repaint in the DOM with each render.

How to Avoid Re-rendering Caused by Callback Function Props

· 7 min read
Hyunmo Ahn
Front End Engineer @ Line+

In React, when passing a function as component props, one needs to be careful with managing references to avoid unnecessary re-renders. Although most case we use useCallback to prevent unnecessary re-renders, I found an alternative solution sharing.

The code that inspired this article is radix-ui/primitives's useCallbackRef. This article will discuss the use cases and logic of useCallbackRef.

Below is the useCallbackRef code we are going to discuss. Can you guess in what situations it might be used?

// useCallbackRef.js
import { useRef, useEffect, useMemo } from 'react';

export function useCallbackRef(callback) {
const callbackRef = useRef(callback);

useEffect(() => {
callbackRef.current = callback;
});

return useMemo(() => ((...args) => callbackRef.current?.(...args)), []);
}