Jack Hu
Jack Hu

Reputation: 1373

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

Upvotes: 3

Views: 2441

Answers (1)

Brenton
Brenton

Reputation: 84

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

Upvotes: 2

Related Questions