useUser

Read the signed-in customer's profile and tell guests from signed-in customers.

Use useUser when a component must greet the customer, show their avatar, or behave differently for guests and signed-in customers.

Example

app/components/layout/AccountLink.tsx
import { useUser } from '@salla.sa/twilight-theme-engine/hooks/useUser';

export function AccountLink() {
  const { isLoggedIn, data: user } = useUser();

  if (!isLoggedIn) return <a href="/login">Sign in</a>;
  return <a href="/account">{user ? `Hello, ${user.first_name}` : 'My account'}</a>;
}

API

function useUser(): UseUserReturn;

type UseUserReturn = UseQueryResult<User | null> & {
  isLoggedIn: boolean;
};

The hook takes no arguments. It returns a React Query result plus isLoggedIn.

PropTypeDescription
isLoggedInbooleantrue when the customer has an auth token. It does not mean the profile has loaded or the token is still valid.
dataUser | nullThe profile. null for guests, while loading, and when the request fails.
isLoadingbooleantrue while the first profile request runs. Always false for guests.
isFetchingbooleantrue during any fetch, including refetches.
refetch() => Promise<...>Loads the profile again, for example after the customer edits it.

The rest of the React Query result (status, error, fetchStatus) is also there. For the User fields see User data.

Gotchas

  • The engine reads the auth token from its own context, so isLoggedIn is correct on the first render, during server rendering as well.
  • The profile request only runs when there is a token. For guests no request is sent and data stays null.
  • If the request fails, data is null and error stays empty, because the API module turns failures into null. Treat "signed in but no data" as "not loaded".
  • User has a type field of "guest" or "user". The hook only returns "user" objects, so use isLoggedIn to detect guests.
  • The hook needs the engine providers at the root of your app, as in a normal theme.

Next

On this page