react-use-lifecycle-hooksdeprecated

Use declarative react lifecycle hooks e.g componentDidMount using useComponentDidMount hook instead of useEffect

Usage no npm install needed!

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

README

Lifecycle Hooks

CircleCI Npm Codecov Licence

Use old react lifecycle hooks componentDidMount, componentDidUpdate etc with new react hooks api using useDidMount, useDidUpdate etc instead of using useEffect.

Motivation

Using useEffect with second param an empty array instead of componentDidMount makes our code less declarative. Same for other lifecycle hooks. Using custom hooks of this library we can replace useEffect for most cases resulting in more declarative code.
But we can use the same useEffect function for both declaring componentDidMount and componentWillUnmount. For this reason this library provides useDidMountAndWillUnmount, useDidUpdateAndWillUnmount hooks etc.

Using this library:

import {useComponentDidMount} from 'react-use-lifecycle-hooks'

const UserStatus = () => {
    useComponentDidMount(subscribeToUserStatus)
    return null
}

Using useEffect hook:

const UserStatus = () => {
    useEffect(()=> {
       subscribeToUseStatus()
    },[])
    
    return null
}

Also you can import every hook from its own file in order to not use every hook in your codebase.

e.g: import useComponentDidMount from 'react-use-lifecycle-hooks/dist/useComponentDidMount'

Install

  • Using yarn
    yarn add react-use-lifecycle-hooks

  • Using npm
    npm install react-use-lifecycle-hooks

API

Every lifecycle hook can be used more than one time in the same function.

Prerequisites

In order to use this library a React version >=16.8.0 is required which introduce react hooks