Skip to content

elissaioskon/react-use-lifecycle-hooks

Repository files navigation

This library is DEPRECATED and no longer maintained

Reason is:

The question is not "when does this effect run" the question is "with which state does this effect synchronize with" Please check the discussion here

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