UseRef, UseMemo, UseCallback: fully explained

Satyarthchhabra
6 min readAug 28, 2021

--

So hooks were introduced to use lifecycle methods and state inside of the functional components. We will be discussing useRef, useMemo, useCallBack, useImperativeHandle,useLayoutEffect, useDebugValue, all with code examples, concept, and practical use case scenarios.

UseRef Hook

Most developers use the useRef hook only to create a reference of the element . an example of the same is demonstrated below

So in this example, it is shown in line 4 a reference is created (basically, in reference, an object is created, and its current property is initialized to null ). In line no 8, this current value of reference is initialized to the input component.

So in the above case, we are not using the actual power of the useRef hook.

Suppose you want to count how many times a component re-renders. Take a minute and try to find the possible way. So now some newbie developers would say that we can create a state variable counter and update its value in useEffect hook, but this is not the correct way because as soon as you will update the value of the counter as the counter is state variable so when its value will update it will also lead to re-rendering of component leading to an infinite loop. Basically, a ref can store a value and change itself without re-rendering the component. will show this below

So here we declare a ref counter in line 5, a state in line 6 (the state is just to make the component re-render many times so that we can count it ). Not on line 7 a useEffect is declared with no dependency, which means that it will work on both componentDidMount and componentDidUpdate (basically, it will run on every re-render).So now, when we press the button, the component will re-render, and the count will increase.

suppose you are working on a very scalable app, there is a large component, and in it you want to update and persist a value(note: this updated value will not be displayed on the screen as ref are updated by shallow re-rendering), but you don’t want the whole component to re-render. Here is an example of this.

now let’s discuss some other case .suppose you wanna display the previous value of the state so you can do it something like this

if we need to pass the reference to another component then in that case we use react.forwardRef . it takes 2 parameters first are props and second is reference . by the way it’s nothing special and you can get more info regarding it here .

So by now, I have given you a broad idea of how you can use useRef. if you need something more , check out here

UseMemo

So suppose you have a very computation heavy task which you don’t want to perform on every render or there are some firebase calls which you can’t make many times as firebase bills according to read and write operations performed on the database . So in this case we can use the memoization concept which states that if the values passed in the function are the same as of the previous value the function will not run again and instead the value will be returned from the cache.

So basically useMemo hook takes 2 parameters one is a function which needs to be memoized and second the array of dependencies . if the value of the dependency will change then the function will be called else it will not be called. One thing to be noted here is we cannot pass the function which has the side effects hence the function needs to be pure . you can understand this as the functions which create effect on other components should not be passed in useMemo hook .

Some cons of useMemo are listed below

  • The hook itself is a very complex logic and react is also very fast and performance optimized so don’t use hooks until you yourself feel the site is laggy .because there would be sometimes when you will use useMemo hook and still the performance will not come good instead you would have made the logic more complex and have introduced more bugs
  • The official react team also suggest it to use very carefully and only where its needed

So basically there are 2 major practical use Cases of this hook .

  • First is to memorize the result obtained by a long time taking function. And only recall the function if the dependency of the function changes . you can get it example here with well explanation
  • The second case where it is used is a bit tricky and you would not come across it daily which is to maintain the referential equality of the value .

Referential equality

So lets understand this from the code presented above . so there is nothing new when we see line no 20 . as the strings are the same it is giving the output to be true . the things become complex when we see line 23 and line 27 . as in case of the functions and objects the === operator does shallow comparison . In shallow comparison the values are not compared instead their references are compared . as in line 6 we are creating the variable with the reference of the previous variable therefore in line 28 the comparison gives true . so for values we refer this phenomenon and referential equality of value and in functions we refer this as referential equality of functions

So what happens in react , suppose you have declared a very heavy function , when re render will occur the js will create a new function every times the re-render will occur . hence this will lead to unnecessary creations of many copies of the expensive function which will make the app slow due to high memory consumption .same goes with the normal declaration of variable also

The below code will help in preserving the referential integrity of the value

UseCallBack

So basically this hook is almost same of useMemo Hook the only difference is that it is used to memoize a callback function and useMemo is used to memoize the result obtained from the function . all the conditions and the drawbacks also remain the same . as the usememo is sometime used to preserve the referential equality of the value the useCallback is used to preserve the referential equality of the function . an example is attached below

Volla, you have learned three react important hooks and now you are ready to optimize your code to the fullest . just remember on thing use these hooks only when its necessary , because they comes at the cost of introducing high level of complexity in the code and my unusual behaviors in the app . I will talk about the left 3 hooks in my next blog and till then happy coding .

--

--

Satyarthchhabra

web developer who loves to travel and explain concepts