useFirstVisit
React hook to detect if it is the user's first visit.
Add the hook via the CLI:
sh
npx @novajslabs/cli add useFirstVisit
sh
npx @novajslabs/cli add useFirstVisit
sh
pnpm dlx @novajslabs/cli add useFirstVisit
Or copy and paste the code into your project:
ts
import { useState, useEffect } from "react";
export const useFirstVisit = (): boolean => {
const [isFirstVisit, setIsFirstVisit] = useState<boolean>(false);
useEffect(() => {
const firstVisit = localStorage.getItem("firstVisit");
if (firstVisit === null) {
localStorage.setItem("firstVisit", "false");
setIsFirstVisit(true);
}
}, []);
return isFirstVisit;
};
js
import { useState, useEffect } from "react";
export const useFirstVisit = () => {
const [isFirstVisit, setIsFirstVisit] = useState(false);
useEffect(() => {
const firstVisit = localStorage.getItem("firstVisit");
if (firstVisit === null) {
localStorage.setItem("firstVisit", "false");
setIsFirstVisit(true);
}
}, []);
return isFirstVisit;
};
Requirements
React 16.8 or higher
Return values
isFirstVisit
Type: boolean
Represents whether it is the user's first visit (true
) or not (false
).
Example
tsx
import { useFirstVisit } from "./hooks/useFirstVisit";
const App = () => {
const isFirstVisit = useFirstVisit();
return <p>{isFirstVisit ? "Your first visit" : "Not your first visit"}</p>;
};
export default App;
Use cases
Here are some use cases where this React hook is useful:
- Displaying a welcome message or introductory tutorial for first-time visitors to a web application
- Providing personalized onboarding experiences for users accessing a platform for the first time
- Offering special promotions or discounts to users during their initial visit to an e-commerce website
- Tracking user engagement metrics by distinguishing between first-time and returning visitors on a blog or content-based site