The useOnUnmount Hook

The useOnUnmount Hook has a similar effect to the componentWillUnmount life cycle. It is used as follows:

import React from 'react'
import { useOnUnmount } from 'react-hookedup'

export default function UseOnUnmount () {
useOnUnmount(() => console.log('unmounting'))

return <div>click the "unmount" button above and look at the console</div>
}

The preceding code will output unmounting to the console when the component gets unmounted (before the React component is removed from the DOM).

If you remember from Chapter 4Using the Reducer and Effect Hooks, we can return a cleanup function from the useEffect Hook, which will be called when the component unmounts. This means that we could alternatively implement the useOnMount Hook using useEffect, as follows:

import React, { useEffect } from 'react'

export default function OnUnmountWithEffect () {
useEffect(() => {
return () => console.log('unmounting with effect')
}, [])

return <div>click the "unmount" button above and look at the console</div>
}

As we can see, using the cleanup function that is returned from an Effect Hook, with an empty array as the second argument, has the same effect as the useOnUnmount Hook, or the componentWillUnmount life cycle method.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.137.185.180