useActivityMount

This Hook will be released with v1.13.0 soon.

A React Hook that runs a function only once when the component mounts in an Activity component.

Unlike useMount, this hook ensures the callback is executed only once strictly, even when the Activity is hidden and shown again. This is particularly useful for initialization logic that should only run once in Activity contexts, not every time the component becomes visible.

Demo

Source

Comparison: useActivityMount vs useMount

useActivityMount count:
0
useMount count:
0

Toggle the Activity to see the difference:

  • useActivityMount only executes once (initial mount)
  • useMount executes every time Activity becomes visible

Usage

See API for more details.

Source

Click links below to view source on GitHub.

API

useActivityMount(callback)

Callback

A function that will be called when the component mounts, can be async.

The callback will only execute once when the component first mounts, and will NOT re-execute when the Activity is shown again after being hidden.

Key Differences

vs useMount

HookBehavior in ActivityUse Case
useMountRuns when Activity becomes visibleUse for side effects that should happen every time content is shown
useActivityMountRuns only once on first mountUse for initialization logic that should only run once (e.g., data fetching, subscriptions)

Example Comparison

import { Activity } from 'react'
import { useMount, useActivityMount } from '@shined/react-use'

function Component() {
  // Runs every time Activity becomes visible
  useMount(() => {
    console.log('Activity is now visible')
  })

  // Runs only once when component first mounts
  useActivityMount(() => {
    console.log('Component initialized')
    fetchInitialData()
  })

  return <div>Content</div>
}

Use Cases

  1. Initial Data Fetching: Fetch data once when the component is first mounted, not every time it becomes visible
  2. Subscriptions: Set up event listeners or subscriptions that should persist across visibility changes
  3. Analytics: Track initial component mount events without double-counting
  4. Resource Initialization: Initialize expensive resources only once

Notes

TIP

This hook internally uses useMount with strictOnce=true, which ensures the callback only runs once by using a ref to track execution status.

INFO

The Activity API is a React feature that allows components to be hidden (using display: none) while preserving their state. This is different from unmounting, where the component is completely removed from the DOM.