Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

Sorry, you do not have permission to ask a question, You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please type your username.

Please type your E-Mail.

Please choose an appropriate title for the post.

Please choose the appropriate section so your post can be easily searched.

Please choose suitable Keywords Ex: post, video.

Browse

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Navigation

  • Home
  • About Us
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • About Us
  • Contact Us
Home/ Questions/Q 7375

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Latest Questions

Author
  • 60k
Author
Asked: November 28, 20242024-11-28T03:14:07+00:00 2024-11-28T03:14:07+00:00

When to use useMemo and useCallback in React?

  • 60k

These two React hooks, useMemo and useCallback are useful when you’re dealing with expensive operations (that is, operations that are very complex and take a lot of time and resources, like CPU.)

If you include one of those expensive operations inside a React component, these costly tasks will run every time the component re-renders, making the application slower.

Those two hooks help to optimize the app by running the costly operation and storing the result in a cache. The next time the component re-renders, it won't run the operation. Instead, it will return the result from the cache.

This is how useMemo works

Let's suppose that we have this expensive operation and a React component that uses it:

function uselessExpensiveOperation(input) {     const someBigArray = [];     for (let i = 0; i < 5_000_000; i++) {         someBigArray.push(input * i);     }     return someBigArray; }  function SomeReactComponent() {     const expensiveOperationResult = uselessExpensiveOperation(3);     const output = expensiveOperationResult         .slice(0, 5)         .map(number => <li key={ number }>{ number }</li>);      return <ul>{ output }</ul>; } 
Enter fullscreen mode Exit fullscreen mode

This example function can take many seconds to run. It returns an array of 5,000,000 numbers in which the value of each number depends on the number you pass as an argument. If you use uselessExpensiveOperation in a React component directly, every time React calls that component during the render process, it will run the expensive operation.

Now, this is what happens if you use the useMemo hook to store the value in cache:

function SomeReactComponent() {     const expensiveOperationResult = useMemo(         function() {             return uselessExpensiveOperation(3);         },         []     );     const output = expensiveOperationResult         .slice(0, 5)         .map(number => <li key={ number }>{ number }</li>);      return <ul>{ output }</ul>; } 
Enter fullscreen mode Exit fullscreen mode

The first argument of useMemo is the function that contains the expensive operation, and the second argument is an array of dependencies. If the value of any of the dependencies changes, React will delete the cache and will run the expensive task.

The idea of the dependencies array is that you should include the variables that your expensive operation needs. In the example, the expensive operation doesn't have any dependency, so the array is empty.

How to use the useCallback hook

This hook is very similar to useMemo, but it stores functions in the cache. You could do it using useMemo, but the syntax is a little easier with useCallback:

function SomeReactComponent() {     const cachedFunction = useCallback(         function originalFunction() {             return "some value";         },         []     );      return <div>{ cachedFunction() }</div> } 
Enter fullscreen mode Exit fullscreen mode

Now, when should you use it? First, I'll explain a special React function, React.memo. This function works like useMemo, but stores React components in the cache to prevent unneeded rendering. This is how it works:

const cachedComponent = React.memo(     function SomeReactComponent(props) {         return <div>Hello, { props.firstName }!</div>     } ); 
Enter fullscreen mode Exit fullscreen mode

The component will be stored in the cache until some of the props change. If that happens, it will re-render it and store it in cache again.

But there's a problem if one of the props is a function that was created in a parent component. Each time the parent component re-renders, the inner function is created again, and is considered as a different function, even if the code hasn't changed.

Therefore, when you pass the “different” function as a prop to the cached component, it will trigger an unneeded re-render.

If you use the useCallback hook, you create the function the first time the component is rendered only. When the component is rendered again it will just retrieve the function from the cache, and this time it will be the same function, and it won't trigger the re-rendering in the child component.

Don't overoptimize

A common mistake that some developers do is to use these hooks (and other optimization techniques) even when they're not needed, trying to prevent performance problems. But that's not recommended because it makes the code more complex (and therefore, harder to maintain) and in some cases, it even performs worse.

You should apply these techniques after you find a performance problem. When something isn't running as fast as you would like, investigate where the bottleneck is and optimize that part.


Free JavaScript Newsletter! Every other Monday, easy and actionable steps to level up your JavaScript skills. Click here to subscribe

javascriptreactwebdev
  • 0 0 Answers
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

Sidebar

Ask A Question

Stats

  • Questions 4k
  • Answers 0
  • Best Answers 0
  • Users 2k
  • Popular
  • Answers
  • Author

    ES6 - A beginners guide - Template Literals

    • 0 Answers
  • Author

    Understanding Higher Order Functions in JavaScript.

    • 0 Answers
  • Author

    Build a custom video chat app with Daily and Vue.js

    • 0 Answers

Top Members

Samantha Carter

Samantha Carter

  • 0 Questions
  • 20 Points
Begginer
Ella Lewis

Ella Lewis

  • 0 Questions
  • 20 Points
Begginer
Isaac Anderson

Isaac Anderson

  • 0 Questions
  • 20 Points
Begginer

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help

Footer

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore, ask, and connect. Join our vibrant Q&A community today!

About Us

  • About Us
  • Contact Us
  • All Users

Legal Stuff

  • Terms of Use
  • Privacy Policy
  • Cookie Policy

Help

  • Knowledge Base
  • Support

Follow

© 2022 Querify Question. All Rights Reserved

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.