README
Lifecycle Hooks
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-hooksUsing npm
npm install react-use-lifecycle-hooks
API
useDidMount
— same with componentDidMountuseWillUnmount
— same with componentWillUnmountuseDidMountAndWillUnmount
— same with componentDidMount & componentWillUnmountuseDidUpdate
— same with componentDidUpdateuseDidUpdateAndWillUnmount
— same with componentDidUpdate & componentWillUnmount
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