Hello ReactJS friends,
In today’s blog, we will learn about useMemo Hook in ReactJS.
Previously we have discussed various types of hooks in ReactJS.
Contents
React useMemo Hook
The React useMemo Hook is used in the functional component and returns a memoized value. Memoization is used when you want to avoid recomputing the function for the next time for a given set of arguments. The memoization function remembers the result of a given set of inputs, so when the parameters are passed again, it returns the stored result without computing the function.
useMemo() is a built-in React hook that accepts two arguments — a function compute that computes a result and the dependencies array
Syntax of useMemo Hook in ReactJS:
1 2 3 4 5 6 |
const memoizedResult = useMemo(compute, dependencies); const memoizedResult = useMemo(() => { return expensiveFunction(propA, propB); }, [propA, propB]); |
Example of useMemo Hook in ReactJS:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
import { useState } from 'react'; export function CalculateFactorial() { const [number, setNumber] = useState(1); const [inc, setInc] = useState(0); const factorial = factorialOf(number); const onChange = event => { setNumber(Number(event.target.value)); }; const onClick = () => setInc(i => i + 1); return ( <div> Factorial of <input type="number" value={number} onChange={onChange} /> is {factorial} <button onClick={onClick}>Re-render</button> </div> ); } function factorialOf(n) { console.log('factorialOf(n) called!'); return n <= 0 ? 1 : n * factorialOf(n - 1); } |
Conclusion:
This was all about the useMemo hook in ReactJS. If you have any doubts, kindly get in touch with me through the comment section. To learn more about ReactJS, stay connected with us.
Happy Coding!