I'm using the why-did-you-render package to debug some performance issues in my react app. I'm getting the following console message regarding why my XDrag component is re-rendering:
XDrag
defaultNotifier.js:40 {XDrag: ƒ} "Re-rendered because of props changes:"
defaultNotifier.js:45 props.children
defaultNotifier.js:49 different React elements (remember that the <jsx/> syntax always produces a *NEW* immutable React element so a component that receives <jsx/> as props always re-renders). (more info here)
defaultNotifier.js:52 {prev children: {…}} "!==" {next children: {…}}
In the article linked to in this message, they suggest using a "pure wrapper" component around our original component to avoid this rerender:
class PureFatherWrapper extends React.PureComponent{ render(){ return ( <PureFather> <SomeChild/> </PureFather> ) } }
- What exactly do they mean by a pure wrapper/ pure component? How is a pure component different from other kinds of components?
- Why doe this pure wrapper avoid a re-render?
- How could I implement a Pure Wrapper for my XDrag Component?
import React, { FC, ReactNode } from "react";
import { Draggable, DraggableProps } from "react-beautiful-dnd";
interface IXDrag extends Omit<DraggableProps, "children"> {
className?: string;
children: ReactNode;
dragAll?: boolean;
}
const XDrag: FC<IXDrag> = ({ className, children, dragAll, ...props }) => {
console.log(React.isValidElement(children));
if (!React.isValidElement(children)) return <div />;
return (
<Draggable {...props}>
{(provided, snapshot) => {
const dragHandleProps = dragAll ? provided.dragHandleProps : {};
return (
<tr
className={className}
ref={provided.innerRef}
{...provided.draggableProps}
{...dragHandleProps}
>
{React.cloneElement(children, { provided })}
</tr>
);
}}
</Draggable>
);
};
Using XDrag:
import React from "react";
import { useStoreState } from "../../hooks";
import XDrag from "../XDrag";
import TableHeader from "./TableHeader";
const ContentTable = () => {
const cardItems = useStoreState(
(state) => state.appModel.activeCards
);
return (
<table>
<tbody>
<tr>
<TableHeader
title={"URL"}
/>
</tr>
{cardItems.map((card, i) => {
return (
<XDrag
draggableId={card.sourceId}
index={i}
key={i.toString()}
isDragDisabled={card.isActive}
>
<td>{card.src}</td>
</XDrag>
);
})}
</tbody>
</table>
);
};
Some Context:
I'm using the react beautiful dnd library to create some draggable rows in a table. Each XDrag provides a <tr> for all the <td>s.