Skip to content

kunukn/use-mount

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

43 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

use-mount

About

ReactJS Mount and UnMount callback hook.

let ref = useMount({ onMount, onUnmount });
/*
 onMount is an optional callback function,
 onUnmount is an optional callback function.
 The ref is attached to the component where the callbacks should apply.
*/

Usage example

import useMount from '@kunukn/use-mount';

let MyComponent = ({ children }) => {
  let onMount = node => console.log('I mounted this node in the DOM:', node);
  let onUnmount = node => console.log('I unmounted this node from the DOM:', node);
  let ref = useMount({ onMount, onUnmount });
  return <div ref={ref}>{children}</div>;
};

let App = () => {
  let [isActive, setToggle] = React.useState(false);

  return (
    <div className="App">
      <button onClick={() => setToggle(s => !s)}>toggle</button>
      {isActive && <MyComponent>This is my component</MyComponent>}
    </div>
  );
};

Demo

https://codesandbox.io/s/gifted-murdock-m3rzk

About

React onMount and onUnMount hook

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published