Search code examples
authenticationsupabaseremix.run

Supabase onAuthStateChange keeps triggering (remix)


I was following a tutorial on setting up Supabase auth with Remix, and while I followed the code step by step, I noticed my component is re-rendering in an infinite loop if I use the following:

const [supabase] = useState(() => createBrowserClient(env.SUPABASE_URL, env.SUPABASE_ANON_KEY));
const revalidator = useRevalidator();

// useEffect only depends on revalidator and supabase (which are memoized)
useEffect(() => {
  const { data: { subscription } } = supabase.auth.onAuthStateChange((event) => {
    console.log(event)
    // Revalidate or trigger page refresh when auth state changes
    revalidator.revalidate();
  });

  return () => subscription.unsubscribe(); // Clean up the subscription when component unmounts
}, [revalidator, supabase]);

The event is always INITIAL_SESSION with just one SIGNED_IN (of course) when I enter the page from a magic link. Is this the expected behavior? I obviously don't want the component to keep re-rendering.


Solution

  • You have the useEffect running every time the revalidator changes, but you are revalidating inside that useEffect. Every time you run it the useEffect is revalidating it, causing it to rerun again.