useComponentDidMount

React, Hooks, Effect

Executes a callback immediately after a component is mounted.

  • Use useEffect() with an empty array as the second argument to execute the provided callback only once when the component is mounted.
  • Behaves like the componentDidMount() lifecycle method of class components.
const useComponentDidMount = onMountHandler => {
  React.useEffect(() => {
    onMountHandler();
  }, []);
};
Examples
const Mounter = () => {
  useComponentDidMount(() => console.log('Component did mount'));

  return <div>Check the console!</div>;
};

ReactDOM.render(<Mounter />, document.getElementById('root'));
View on GitHub

Recommended snippets

  • Executes a callback immediately before a component is unmounted and destroyed.

  • useClickInside

    React, Hooks

    Handles the event of clicking inside the wrapped component.

  • useClickOutside

    React, Hooks

    Handles the event of clicking outside of the wrapped component.