use-is-mounted-ref

📦 useIsMountedRef() is a React Hook to check when the component is mounted.

MIT License

Stars
43

Table of Contents

Motivation

  • Avoid memory leaks setting states when component are unmounted;
  • Control when component already mounted;
  • Common error when setting state to unmounted component:
Warning: Can only update a mounted or mounting component. This usually means you called setState, replaceState, or forceUpdate on an unmounted component. This is a no-op.

Usage

To start using the use-is-mounted-ref in your project, first install in your project:

yarn add use-is-mounted-ref or npm install use-is-mounted-ref

import { useState, useEffect } from 'react';
import useIsMountedRef from 'use-is-mounted-ref';

function App() {
  const isMountedRef = useIsMountedRef();

  const initialState = {
    loading: false,
    error: false,
    data: [],
  };

  const [state, setState] = useState(initialState);

  useEffect(() => {
    fetch('https://www.reddit.com/.json')
      .then((response) => response.json())
      .then(({ data }) => {
        if (isMountedRef.current) {
          setState((prevState) => {
            return {
              ...prevState,
              loading: false,
              data,
            };
          });
        }
      })
      .catch((err) => {
        if (isMountedRef.current) {
          setState((prevState) => {
            return { ...prevState, loading: false, error: true };
          });
        }
      });
  }, []);

  return state.loading ? 'Loading...' : 'Found Data!';
}

export default App;

Component Lifecycle Overview

flowchart TD
    subgraph "Component Lifecycle"
        direction TB
        A1["Component Mounted"] --> A2["useIsMountedRef Hook"]
        A2 --> B1["useRef(false)"]
        B1 --> C1["useEffect Hook"]
        C1 --> D1["isMountedRef.current = true"]
        
        C1 --> E1["Component Unmounted"]
        E1 --> F1["Cleanup function"]
        F1 --> G1["isMountedRef.current = false"]
    end
    
    subgraph "Usage in Component"
        H1["Check if Component is Mounted"]
        H1 --> I1{isMountedRef.current ?}
        I1 -- "True" --> J1["Perform Mounted Actions"]
        I1 -- "False" --> K1["Do Not Perform Actions"]
    end

Contributing

Please read CONTRIBUTING.md for details on our code of conduct, and the process for submitting pull requests to us.

Bugs and Sugestions

Report bugs or do suggestions using the issues.

License

MIT License © helderberto

Badges
Extracted from project README
build version MIT License downloads