What's really the practical difference between client:load and client:only directives in Astro?

682 Views Asked by At

I have a React component within an Astro page calling the object window but it's getting broken because window is not defined when the page is using client:load, although it works with client:only.

Astro docs mention that client:only and client:load act similar. So, respecting that I'm a newbie on Astro, I wonder why window is not defined when the page uses client:load.

If you are an Astro expert, would you gently explain the practical difference between these two client directives?

In advance, thanks!

index.astro

---
import '@/styles/globals.css'
import MyComponent from '@/components/ui/mycomponent'
---

<html lang="en">
    <head>
        <meta charset="utf-8" />
        <link rel="icon" type="image/svg+xml" href="./favicon.icns" />
        <meta name="viewport" content="width=device-width" />
        <meta name="generator" content={Astro.generator} />
        <title>My App</title>
    </head>
    <body>
        <MyComponent client:load />
    </body>
</html>

mycomponent.tsx

const isHomePage = () => {
  const currentRoute = window.location.pathname;
  return currentRoute === '/';
}

export default function MyComponent() {  
  return (
    <div>
      {
        isHomePage() ? 'Home Page' : 'Other Page'
      }
    </div>
  )
}

Error:

enter image description here

1

There are 1 best solutions below

0
On

As mentioned in the bug message, you need to use the React lifecycle, so your code will be like this:

export default function MyComponent() {
  const [isHomePage, setIsHomePage] = useState(false);
  useEffect(() => {
    const currentRoute = window.location.pathname;
    setIsHomePage(currentRoute === '/');
  }, []);

  return <div>{isHomePage ? 'Home Page' : 'Other Page'}</div>;
}

for the difference between client:load and client:only check this link