Accessing the same SWR hook in nested components #1782
-
I am wondering whether we use the SWR hooks in the intended way. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 6 replies
-
Yeah... but it depends... consider this example: import useSWR from "swr";
const useData = () => {
return useSWR<string>("data", () => {
return new Promise((resolve) => setTimeout(resolve, 1000, "data"));
});
};
const Parent: React.FC = ({ children }) => {
const { data } = useData();
console.count("Parent");
return (
<section>
<h1>Parent {data}</h1>
{children}
<Child label="inner" />
</section>
);
};
const Child = ({ label }: { label: string }) => {
const { data } = useData();
console.count(`Child: ${label}`);
return <p>{data}</p>;
};
const Home: NextPage = () => {
return (
<div>
<Parent>
<Child label="1" />
<Child label="2" />
<Child label="3" />
</Parent>
</div>
);
}; This would log (without strict mode):
But we shouldn't let the logs dictate our understanding. We can profile this using the React Dev Tools, which is what you should do in your use cases. The Profiler would show about 7 frames (using NextJS).
This means that using composition, in this case, prevents re-rendering for children 1,2 and 3, which is not only true for Edit: Using As usual, there's no silver bullet answer. Also, re-rendering is not necessarily that bad, it only means that React collects updates. SWR is highly optimized to prevent re-rendering of callers. And last, but not least, when using this global data solutions, we must remember that, most of the time, components sharing a data slice, are actually using the same data reference. |
Beta Was this translation helpful? Give feedback.
Yeah... but it depends... consider this example: