简体   繁体   中英

How to make useEffect in custom hook trigger only when props changed?

In this video, Dan extract a useDocumentTitle custom hook, but I found the custom hook trigger multiple times, sometimes it is unnecessary. The question is how to trigger the useEffect function only when the key props changed?

It could be realized like this without using custom hooks:

useEffect(() => {
  console.log('useDocumentTitle ')

  document.title = myTitle);
}, [someProp])

But how to do it with custom hooks?

https://youtu.be/dpw9EHDh2bM?t=2969

You can simply pass the key as a separate argument and have the code you used above in the custom hook.

function useCustomHook({someProp, myTitle}) {
    useEffect(() => {
        console.log('useDocumentTitle ')

        document.title = myTitle);
    }, [someProp])
}

you would use it like:

const customHookOptions = {someProp: props.key, myTitle: 'the title'}
useCustomHook(customHookOptions)

Another thing you are able to do is only re-render the entire component if props change by using react.memo() https://reactjs.org/docs/react-api.html#reactmemo

There is also a hook useMemo which has it's own place for doing heavy work https://reactjs.org/docs/hooks-reference.html#usememo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM