use-has-mounted
v1.0.5
Published
React hook for knowing if a component has mounted yet
Downloads
1
Readme
use-has-mounted
🌠 React hook for knowing if a component has mounted yet… for when you'd otherwise need
componentDidMount
and state.
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