Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

BorisTheTripper's avatar

Should usePage() be avoided if the prop I need is page-specific?

Let's say I have a page called User, and it accepts a prop called user that is only available on this page. I also have a component called UserProfile inside the page. Let's assume that UserProfile is nested so deeply within User that prop-drilling becomes non-trivial.

I figured this is a good use case for usePage(). However, when I navigate away from User to another page (one that doesn't have the user prop), the UserProfile component gets re-rendered, potentially causing the application to break (like if I try to access user.username).

The only quick fix I've been able to come up with is something like this:

export function UserProfile() {
  const { user } = usePage().props;
  if (!user) return;

  // ...
}

But this doesn't feel right because it forces me to return prematurely, potentially before other hooks are invoked, which isn't a recommended pattern in React.

Does this mean that I should avoid usePage() altogether in situations like these? Or should I only rely on prop-drilling, even when it's inconvenient?

0 likes
3 replies
gych's avatar

So the UserProfile component is used on multiple pages? Depending on how many pages you could share the prop via the share() method in HandleInertiaRequests.php

After that the prop will be available on all pages. If you only need it on specific pages you can add a condition in HandleInertiaRequests.php to only share the user data on specific pages.

After that you can also access the shared data via usePage()

BorisTheTripper's avatar

@gych No, in this case the user object isn't meant to be available on all pages. It's just an object containing some info on the user whose profile is currently being viewed, specifically on the User page.

azimidev's avatar

I would say If you’re dealing with deeply nested components and want to avoid prop-drilling, Context is a clean and scalable solution that keeps the data local to the page but accessible by deeply nested components.

Using usePage() is fine, but you’ll need to guard it, as you’re doing, to avoid accessing props that may not exist after navigation.

Avoid relying solely on usePage() if the prop is specific to a page or component that can be removed during navigation.

Please or to participate in this conversation.