开发者社区> 镜像站> NPM> use-has-mounted
use-has-mounted
React hook for knowing if a component has mounted yet
Last updated 2 years ago by blakek .
MIT · Repository · Original npm · Tarball · package.json
$ cnpm install use-has-mounted 
SYNC missed versions from official npm registry.

use-has-mounted

???? React hook for knowing if a component has mounted yet… for when you'd otherwise need componentDidMount and state.

Build status NPM

Use to know if a component has mounted.

Instead of using componentDidMount and a variable in state to know if a component has mounted or not, you can know in two lines:

import useHasMounted from 'use-has-mounted';

const hasMounted = useHasMounted();

Why was this created?

There are several situations where you just need a stylistic component that needs to know if it has been rendered. For example, if you need to use different classes in the browser than initially created on the server, you may wait until the component has mounted before making changes so ReactDOM.hydrate() works properly.

Mainly, I wanted to see if the process for publishing a hook would be much different from other packages. This one of the simplest, still useful hooks I could think of.

Also, this is a simple, fast, small way of accomplishing what would have been done before as componentDidMount + state.

Usage

import React from 'react'; // At least v16.8
import useHasMounted from 'use-has-mounted';
import isCurrentPath from './navlink-is-active';

// Example: a link that changes classes if the page it links to is the current page
function NavLink({ path }) {
  // `useHasMounted` usage
  // To run before initial paint, pass `true` as the only argument
  const hasMounted = useHasMounted();
  const className =
    hasMounted && isCurrentPath(path) ? '.navlink__active' : '.navlink';

  return (
    <a href={path} className={className}>
      {hasMounted}
    </a>
  );
}

API

useHasMounted(beforePaint)

beforePaint

Type: Boolean
Default: false

If true, the call runs during the same phase as componentDidMount did: before the browser has had a chance to paint. This also means other visual updates are blocked until this finishes. Uses useLayoutEffect().

If false, this runs asynchronously after an initial paint. That means visual updates aren't blocked, but any visual changes may flash on the screen between changes. Uses useEffect().

Install

With either Yarn or npm installed, run one of the following:

Yarn:

yarn add use-has-mounted

npm:

npm install --save use-has-mounted

License

MIT

Current Tags

  • 1.0.5                                ...           latest (2 years ago)

3 Versions

  • 1.0.5                                ...           2 years ago
  • 1.0.4                                ...           2 years ago
  • 1.0.2                                ...           2 years ago
Maintainers (1)
Downloads
Today 0
This Week 0
This Month 0
Last Day 0
Last Week 0
Last Month 0
Dependencies (0)
None
Dependents (0)
None