DEV Community

Mohamed Adel
Mohamed Adel

Posted on • Updated on

React optimization: useMemo() , React.memo() & useCallback()

Memo & useCallback

Best performance and optimization training

 

Before optimization

  • Making enviroment with the issue of all components re-rendering

  • Understanding how react works and re-evaluation : re-running everything again in react except states declaring.

  • Difference between re-run/re-evaluate & re-render

    • re-evaluate should work every time and compare
    • re-render works on change only with calling react-dom
    • All react components will re-rerun (not re-render) everytime if we didn't use any optimization

Optimization methods

It's a trial to make re-run/re-evaluate works like re-render on changes only

  1. React.memo()
  • it saves the component states and props to get checked first before the re-run

  • It caches the props and states of the components so using it alot in useless way will make it caching a lot so it will be heavy on runtime.

     

   import React from "react"

   const Component=(props)=>{
    //some javascript
    return (
        //some jsx
    )
   }
   export default React.memo(Component)
Enter fullscreen mode Exit fullscreen mode
  1. useMemo()
  • difference between reference types in Js

     

     let name = "adel"
     let name2 = "adel"
    
     //name === name2 --> true
    
     let obj = {name:"adel"}
     let obj2 = {name:"adel"}
    
     //obj === obj2 --> false
     //objects on different refrences values
    
     let obj3 = obj
     //passing by refrence
    
     //obj === obj3 --> true
    
    • Primitive type
    • Refrence type : Object, array & function

       

  • useMemo is used with arrays, objects & with functions that returns something to fix the problem in re-decleration with every re-reun

     const obj = useMemo(()=>{ return name: "adel" }, [])
    
  • useMemo prevents object re-declaration with new refrence on re-run

  1. useCallback()
  • useCallback() prevents function (with no return) from re-declaration with new refrence on re-rerun

     

   //this won't work it will be re-declared with new refrence every re-run

   const addAge = () => {
     //function logic with no return
   }

   //solution

   const addAge = useCallback(() => {
     //function logic
   }, [])

   return <Component addAge={addAge} />
Enter fullscreen mode Exit fullscreen mode
  • useCallback caches the logic itself not a return value like useMemo

Top comments (0)