Skip to content

Instance returned from hook is not memoized? #144

@adi-works

Description

@adi-works

I'm trying to set a loading state imperatively, but it seems the hook returns a new loader instance each time. I had to remove it as dependency from the effect to stablize the effect. Ideas?

Edit: Looks like I was right:

isRendered: () => NProgress.isRendered(),

import { useEffect, useRef } from 'react';

import { useTopLoader } from 'nextjs-toploader';

export type UseTopLoaderEffectProps = {
    isLoading: boolean;
    forceDone?: boolean;
};

export function useTopLoaderEffect({
    isLoading,
    forceDone = false,
}: UseTopLoaderEffectProps) {
    const loader = useTopLoader();
    const prevLoaderRef = useRef(loader);

    useEffect(() => {
        if (prevLoaderRef.current !== loader) {
            console.log('not the same instance');
            prevLoaderRef.current = loader;
        }
    }, [loader]);

    useEffect(() => {
        if (isLoading) {
            loader?.start();
        } else {
            loader?.done(forceDone);
        }
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [isLoading, forceDone]);
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions