React useMemo example with explanation

useMemo React
import React,{useMemo,useState} from "react";
import "./style.css";

export default function App() {
const [state, setState] = useState(0);
for(let i=1;i<10;i++){
let a=1;
let b = 1;
console.log(useMemo(()=> {console.log('invoked');return a+b},[a,b]))
const callMe=()=>{
return (
<h1>Hello StackBlitz!</h1>
<p onClick={callMe}>Start editing to see some magic happen :)</p>

React component renders every time it’s state changes. In the above example without useMemo the message will be printed(along with value 2) when we click on the message(I know it’s wrong to have onclick on paragraph) nine times.

If we put useMemo in place then the message wont be printed. Instead, memoized value will be presented on the screen(which is 2; nine times!)

About the Author

Pravin Varma

Tech Lead at Calsoft

You may also like these