Search code examples
javascriptreactjsperformanceuse-effect

How to reduce the number of times useEffect is called?


Google's lighthouse tool gave my app an appalling performance score so I've been doing some investigating. I have a component called Home

inside Home I have useEffect (only one) that looks like this

useEffect(() => {
    console.log('rendering in here?') // called 14 times...what?!
    console.log(user.data, 'uvv') // called 13 times...again, What the heck?
}, [user.data])

I know that you put the second argument of , [] to make sure useEffect is only called once the data changes but this is the main part I don't get. when I console log user.data the first 4 console logs are empty arrays. the next 9 are arrays of length 9. so in my head, it should only have called it twice? once for [] and once for [].length(9) so what on earth is going on?

I seriously need to reduce it as it must be killing my performance. let me know if there's anything else I can do to dramatically reduce these calls

this is how I get user.data

const Home = ({ ui, user }) => { // I pass it in here as a prop

const mapState = ({ user }) => ({
    user,
})

and then my component is connected so I just pass it in here


Solution

  • To overcome this scenario, React Hooks also provides functionality called useMemo. You can use useMemo instead useEffect because useMemo cache the instance it renders and whenever it hit for render, it first check into cache to whether any related instance has been available for given deps.. If so, then rather than run entire function it will simply return it from cache.