Search code examples
reactjsreact-hooksswr

React custom hook causes infinite loops


any idea why this custom hook with SWR causes an infinite loop?

export const useOrganization = () => {
  const [data, setData] = useState<OrganizationModel | undefined>();
  const { organizationId } = useParams();
  const { data: dataSWR } = useSWRImmutable<
    AxiosResponse<Omit<OrganizationModel, 'id'>>
  >(`organizations/${organizationId}`, api);

  useEffect(() => {
    if (dataSWR?.data && organizationId) {
      setData({ id: organizationId, ...dataSWR.data });
      console.log({ id: organizationId, ...dataSWR.data });
    }
  });
  return data;
};

I need to fetch data from API and add missing id from URL param. If I use setData(dataSWR.data), everything is fine. The problem occurs when setData({...dataSWR.data}) is used -> loop.


Solution

  • I found the solution - useMemo hook:

    export const useOrganization = () => {
      const { organizationId } = useParams();
      const { data } = useSWRImmutable<
        AxiosResponse<Omit<OrganizationModel, 'id'>>
      >(`organizations/${organizationId}`, api);
    
      const result = useMemo(() => {
        if (data && organizationId) {
          return { id: organizationId, ...data.data };
        }
      }, [data, organizationId]);
      console.log('useOrganization');
      return result;
    };