How to handle first-time visitors
This example demonstrates how to handle first-time visitors using the useFirstVisit
hook.
tsx
import { useFirstVisit } from "./useFirstVisit";
export default function App() {
const isFirstVisit = useFirstVisit();
const handleClick = () => {
if (isFirstVisit) {
alert("Starting the tour...");
} else {
alert("Redirecting to the dashboard...");
}
};
return (
<>
<h1>{isFirstVisit ? "Welcome to our app!" : "Welcome back!"}</h1>
<button onClick={handleClick}>
{isFirstVisit ? "Take a tour" : "Go to the dashboard"}
</button>
</>
);
}
typescript
import { useState } from "react";
export const useFirstVisit = (): boolean => {
const [isFirstVisit, setIsFirstVisit] = useState<boolean>(false);
const firstVisit = localStorage.getItem("firstVisit");
if (firstVisit === null) {
localStorage.setItem("firstVisit", "true");
setIsFirstVisit(true);
}
return isFirstVisit;
};