Sitemap
Nineteenthbrumaire

Nineteenthbrumaire

Anonymous Functions, useEffect, and Infinite Re-renders

Sep 25, 2024

When your useEffect has a dependency on a function like this:

export interface ResourceStatusProps {
children: ReactNode;
loadResources: () => void;
}

export const ResourceStatus: React.FC<ResourceStatusProps> = ({
loadResources,
}: ResourceStatusProps) => {
useEffect(() => {
loadResources();
setTimeout(() => setDelay(false), 400);
}, [loadResources]);

And pass in a prop like this:

      <ResourceStatus
loadResources={() => {
loadNode(params.slug);
loadPerspectives();
}}
>

It will cause an infinite re-render loop.

Get Nineteenthbrumaire’s stories in your inbox

Join Medium for free to get updates from this writer.

This is because the anonymous function is created on each render of the parent component. Fortunately my use case only requires this function to run once, so changing the useEffect dependency to an empty array was the solution.

--

--