Next.js Discord

Discord Forum

template.tsx - useEffect on mount does not fire for page transition

Unanswered
West African Crocodile posted this in #help-forum
Open in Discord
West African CrocodileOP
Hey there. I am using a template.tsx on root level, because I thought its useEffect hook will fire for every route change, because the template remounts. But it does not. In my example, I do not see 'here 2' on route transition, only when reloading the page.

'use client';

import { useEffect } from 'react';

type RootTemplateProps = {
  children: React.ReactNode;
};

export default function RootTemplate({
  children,
}: RootTemplateProps) {
  console.log('here 1');

  useEffect(() => {
    console.log('here 2');
  }, []);

  return <>{children}</>;
}

7 Replies

West African CrocodileOP
So I came up with two workaround:

1) render a child component with the useEffect hook in the template.tsx and give the React element a key:

return (
    <>
      <>{children}</>
      <MyChildComponent key={new Date().getTime()} />
    </>
  );
2)

use pathname from usePathname in the depencency array of the useEffect hook.
But either way, I would have expected to see "here 2" from the initial code snippet. Is this a bug or is this expected behavior?
West African CrocodileOP
And if I need to use 1) or 2), I could do it with the layout.tsx too
Interesting, I do think this is a bug. I would create a bug report here
West African CrocodileOP
Hm ... Can anyone confirm?
West African CrocodileOP