react-lifecycle-hook

Lifecycle hooks for functional components

Usage no npm install needed!

<script type="module">
  import reactLifecycleHook from 'https://cdn.skypack.dev/react-lifecycle-hook';
</script>

README

React Lifecycle Hook

Lifecycle hooks for functional components

Installation

Open a Terminal in the project root and run:

yarn react-lifecycle-hook

or

npm i react-lifecycle-hook

API reference

useComponentDidMount

After all the elements of the page is rendered correctly, this method is called

import { useComponentDidMount } from 'react-lifecycle-hook';

export const YourAwesomeComponent = () => {
  useComponentDidMount(() => {
    fetchData()
    document.addEventListener("click", closeMenu);
  })

  return (
    //...
  )
}

useComponentDidUpdate

Can be useful to perform some action when the state changes

import { useComponentDidUpdate } from 'react-lifecycle-hook';

export const YourAwesomeComponent = () => {
  useComponentDidUpdate(
    (prevProps) => {
      if(prevProps.isOpenModal !== isOpenModal) {
        console.log('Modal state changed')
      }
    },
    { isOpenModal },
  );

  return (
    //...
  )
}

useComponentWillUnmount

useComponentWillUnmount is invoked immediately before a component is unmounted and destroyed

import { useComponentWillUnmount } from 'react-lifecycle-hook';

export const YourAwesomeComponent = () => {
  useComponentWillUnmount(() => {
    document.removeEventListener("click", closeMenu);
  });

  return (
    //...
  )
}