SWR Hooks for User State
What is SWR?
SWR is a React hook library for data fetching. It stands for stale-while-revalidate, it is a strategy to first return the data from cache (stale), then send the fetch request (revalidate), and finally come with the up-to-date data.
Features
- Fast, lightweight and reusable data fetching
- Built-in cache and request deduplication
- Polling and Revalidation
- Error Handling
Implementation
In Assemble Web, we use SWR hooks to manage the user state. These hooks are located in the src/hooks directory. Currently, we have two primary hooks: useUser and useProfile. Each hook allows for custom configuration, enabling you to adjust the behavior of data fetching, such as when to revalidate the data.
Available Hooks
useUser
The useUser hook is used to retrieve the current user's information in functional React components or other hooks. It handles the fetching of the user session, which is managed by our Session Management system.
Usage
To use the useUser hook, import it into the component where you need access to the user data:
import { useUser } from '@/hooks/useUser';
const { isLoggedIn, user } = useUser();
isLoggedIn: A boolean value that indicates whether the user is logged in.user: The user object containing details about the currently authenticated user.
Example usage within a component:
const login = useMemo(
() =>
!isLoggedIn && loginItem?.displayText
? {
displayText: loginItem.displayText,
Element: Link,
href: loginItem.route,
}
: undefined,
[isLoggedIn, loginItem?.displayText, loginItem?.route],
);
We conditionally generate a login item that will only be shown if the user is not logged in and there is a valid loginItem.displayText value.
useProfile
The useProfile hook is used to retrieve the first profile associated with the user, using the user's access token. It can be used alongside useUser to get both user and profile information.
Usage
import { useProfile } from '@/hooks/useProfile';
const { user } = useUser();
const { profile } = useProfile();
You can then use the user and profile objects to display information about the user:
const userMemo = useMemo(
() =>
user?.name
? {
name: user.name,
image: profile?.avatar,
}
: undefined,
[user, profile],
);