Socket
Socket
Sign inDemoInstall

use-is-mounted-ref

Package Overview
Dependencies
3
Maintainers
1
Versions
12
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

    use-is-mounted-ref

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


Version published
Maintainers
1
Install size
11.3 kB
Created

Readme

Source

📦 use-is-mounted-ref

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

build version MIT License downloads


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

Avoid set state when unmounted component:
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;

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 © helderburato

Keywords

FAQs

Last updated on 19 Jan 2022

Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc