I have a component that gets loaded through it's parent's . This component renders its own components - ActionsBar and Collection. When the URL changes and the Outlet gets rerendered - my assumption would be that everything within the comonent would get rerendered, however it appears to only rerender the child components if they have changed.
export default function ComponentLoadedInOutlet() {
  const collectionData = useLoaderData();
  return (
    <div>
      <ActionsBar />
      <Collection data={collectionData} />
    </div>
  )
}
In the above snippet, when the outlet gets reloaded when the URL changes, it is only the Collection component that is being re-rendered because the collectionData has changed.
I would like to know if there's a way to force all the Child components within the outlet to reload, so that I don't have to mess around with resetting lots of state.
Your assumption is correct, everything within the component is re-rendered when the url changes. However there is a difference between re-rendering and re-mounting.
When navigating from one url to another which routes to the same component (i.e. a $dynamic.tsx segment), React will merely re-render the component, rather than unmount / mount the component.
This can be useful if you want to preserve state, however this isn't always desirable.
It's therefore common in React to add a key prop to reset a component hierarchy.
// /products/$slug.tsx
export const loader = ({ request, params }: LoaderArgs) =>
  json({ slug: params.slug });
export default function ProductDetail() {
  const { slug } = useLoaderData<typeof loader>();
  return (
    // NOTE: `key={slug}`
    <div key={slug}>
      <ActionsBar />
    </div>
  );
}
const ActionsBar = () => {
  useEffect(() => {
    // This will re-mount whenever the `slug` changes
    alert("<ActionBar /> mounted");
  }, []);
  return <div>ActionsBar</div>;
};
This will tell React to avoid diffing the new tree with the old tree and instead just blow away the old one, creating a brand new tree & therefore mount cycle.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With