useMemo vs useCallbackWelcome to CodeYourCraft's deep dive into React JS! Today, we'll explore two powerful React hooks - useMemo and useCallback. Let's get started! šÆ
React Hooks are functions that let you use state and other React features without writing a class. They allow you to reuse logic between functions and make your code more efficient. š”
useMemouseMemo is a React Hook that helps optimize your component by memoizing the result of a expensive function call and only re-calculating it when its dependencies change.
const memoizedValue = useMemo(() => {
// expensive computation
complexFunction();
}, [dependency1, dependency2]);š Note: The function you want to memoize goes inside the useMemo function, and dependencies are enclosed in square brackets.
Let's say we have a function that calculates the Fibonacci sequence, which can be quite slow for large numbers. To optimize this, we can use useMemo.
import React, { useState, useMemo } from 'react';
function Fibonacci({ n }) {
const [fib, setFib] = useState([0, 1]);
const fibonacci = useMemo(() => {
const fibArray = Array(n).fill().map((_, i) =>
i < 2 ? i : fib[i - 1] + fib[i - 2]
);
return fibArray;
}, [n]);
return <ul>{fibonacci.map(number => <li key={number}>{number}</li>)}</ul>;
}In this example, useMemo helps us avoid recalculating the Fibonacci sequence every time n changes, making our component more efficient. ā
useCallbackuseCallback is a React Hook that returns a memoized version of the callback that only changes when one of its dependencies changes. This can help prevent unnecessary re-renders in child components.
const memoizedCallback = useCallback(() => {
// your callback function
}, [dependency1, dependency2]);š Note: The callback function you want to memoize goes inside the useCallback function, and dependencies are enclosed in square brackets.
Let's create a parent component that passes a callback to a child component to handle an event. With useCallback, we can prevent the child component from re-rendering unnecessarily.
import React, { useState, useCallback } from 'react';
function ParentComponent() {
const [count, setCount] = useState(0);
const handleClick = useCallback(() => {
setCount(count + 1);
}, [count]);
return (
<ChildComponent onClick={handleClick} count={count} />
);
}
function ChildComponent({ onClick, count }) {
return (
<button onClick={onClick}>
Clicked {count} times
</button>
);
}In this example, useCallback ensures that the handleClick function doesn't change between renders, even though count changes, thus preventing unnecessary re-renders in the child component. ā
What does the `useMemo` hook do in React?
Stay tuned for more in-depth tutorials on CodeYourCraft! We'll explore advanced examples, best practices, and more. Keep coding and learning! š