useFirstVisit

React hook to detect if it is the user's first visit.

Add the hook via the CLI:

npx @novajslabs/cli add useFirstVisit

Or copy and paste the code into your project:

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
}

React 16.8 or higher

  • Name
    isFirstVisit
    Type
    boolean
    Description

    Represents whether it is the user's first visit (true) or not (false).

import { useFirstVisit } from './hooks/useFirstVisit'

const App = () => {
  const isFirstVisit = useFirstVisit()

  return <p>{isFirstVisit ? 'Your first visit' : 'Not your first visit'}</p>
}

export default App

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