Skip to content

Commit 369ee34

Browse files
cursoragentchargome
andcommitted
Optimize withErrorBoundary by adding React.memo to prevent unnecessary rerenders
Co-authored-by: charly.gomez <[email protected]>
1 parent b9849a2 commit 369ee34

File tree

3 files changed

+23
-2
lines changed

3 files changed

+23
-2
lines changed

core

71.6 MB
Binary file not shown.

packages/react/src/errorboundary.tsx

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -222,11 +222,11 @@ function withErrorBoundary<P extends Record<string, any>>(
222222
): React.FC<P> {
223223
const componentDisplayName = WrappedComponent.displayName || WrappedComponent.name || UNKNOWN_COMPONENT;
224224

225-
const Wrapped: React.FC<P> = (props: P) => (
225+
const Wrapped = React.memo<P>((props: P) => (
226226
<ErrorBoundary {...errorBoundaryOptions}>
227227
<WrappedComponent {...props} />
228228
</ErrorBoundary>
229-
);
229+
));
230230

231231
Wrapped.displayName = `errorBoundary(${componentDisplayName})`;
232232

packages/react/test/errorboundary.test.tsx

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -96,6 +96,27 @@ describe('withErrorBoundary', () => {
9696
const Component = withErrorBoundary(() => <h1>Hello World</h1>, { fallback: <h1>fallback</h1> });
9797
expect(Component.displayName).toBe(`errorBoundary(${UNKNOWN_COMPONENT})`);
9898
});
99+
100+
it('prevents unnecessary rerenders with React.memo', () => {
101+
let renderCount = 0;
102+
const TestComponent = ({ value }: { value: string }) => {
103+
renderCount++;
104+
return <div>{value}</div>;
105+
};
106+
107+
const WrappedComponent = withErrorBoundary(TestComponent, { fallback: <h1>fallback</h1> });
108+
109+
const { rerender } = render(<WrappedComponent value="test" />);
110+
expect(renderCount).toBe(1);
111+
112+
// Rerender with same props - should not cause wrapped component to rerender
113+
rerender(<WrappedComponent value="test" />);
114+
expect(renderCount).toBe(1);
115+
116+
// Rerender with different props - should cause wrapped component to rerender
117+
rerender(<WrappedComponent value="different" />);
118+
expect(renderCount).toBe(2);
119+
});
99120
});
100121

101122
describe('ErrorBoundary', () => {

0 commit comments

Comments
 (0)