The useLifecycleHooks Hook

The useLifecycleHooks Hook combines the previous two Hooks into one. We can combine the useOnMount and useOnUnmount Hooks as follows:

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

export default function UseLifecycleHooks () {
useLifecycleHooks({
onMount: () => console.log('lifecycle mounted'),
onUnmount: () => console.log('lifecycle unmounting')
})

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

Alternatively, we could use the two Hooks separately:

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

export default function UseLifecycleHooksSeparate () {
useOnMount(() => console.log('separate lifecycle mounted'))
useOnUnmount(() => console.log('separate lifecycle unmounting'))

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

However, if you have this kind of pattern, I would recommend simply using the useEffect Hook, as follows:

import React, { useEffect } from 'react'

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

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

Using useEffect, we can put our whole effect into a single function, and then simply return a function for cleanup. This pattern is especially useful when we learn about making our own Hooks in the next chapters.

Effects make us think differently about React components. We do not have to think about the life cycle of a component at all. Instead, we think about effects, dependencies, and the cleanup of effects.

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

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