How to Use useEffect, useContext, useRef, useCallback, and useMemo in React.
Aditya Mathur
Posted on March 16, 2023
React is a popular JavaScript framework for building web and mobile applications. One of the key features of React is its ability to manage state and update the user interface in response to changes in state. In this blog post, we'll explore how to use some of React's most powerful hooks: useEffect, useContext, useRef, useCallback, and useMemo.
useEffect
The useEffect hook allows you to run side effects in a functional component. Side effects include things like fetching data from an API, updating the document title, or setting up and cleaning up event listeners. Here's an example of how to use useEffect to fetch data from an API:
import React, { useState, useEffect } from 'react';
function MyComponent() {
const [data, setData] = useState([]);
useEffect(() => {
fetch('<https://api.example.com/data>')
.then(response => response.json())
.then(data => setData(data))
.catch(error => console.error(error));
}, []);
return (
<div>
{data.map(item => (
<div key={item.id}>{item.name}</div>
))}
</div>
);
}
In this example, we use the useState hook to set up a state variable called data and initialize it to an empty array. We then use the useEffect hook to fetch data from an API and update the data state variable with the response. The second argument to useEffect is an array of dependencies that determines when the effect should run. In this case, we pass an empty array to indicate that the effect should only run once, when the component mounts.
We can also clean up after the useEffect hook completes running, you can return a function from the useEffect callback that performs the necessary cleanup. For example, if you set up an event listener in the useEffect hook, you can remove the event listener in the cleanup function:
import React, { useState, useEffect } from 'react';
function MyComponent() {
const [count, setCount] = useState(0);
useEffect(() => {
const handleClick = () => {
setCount(count + 1);
};
window.addEventListener('click', handleClick);
return () => {
window.removeEventListener('click', handleClick);
};
}, [count]);
return (
<div>
Count: {count}
</div>
);
}
In this example, we use the useEffect hook to set up a click event listener on the window object. We then return a cleanup function that removes the event listener. This ensures that the event listener is removed when the component unmounts or when the count state variable changes.
useContext
The useContext hook allows you to consume a context created by a parent component. Context is a way to pass data through the component tree without having to pass props down manually at every level. Here's an example of how to use useContext to consume a theme context:
import React, { useContext } from 'react';
import { ThemeContext } from './theme-context';
function MyComponent() {
const theme = useContext(ThemeContext);
return (
<div style={{ backgroundColor: theme.background, color: theme.text }}>
My Component
</div>
);
}
In this example, we consume a context created by a parent component using the useContext hook. We then use the theme data to style our component.
useRef
The useRef hook allows you to create a mutable container to store a value across renders. This can be useful for accessing DOM elements, managing focus, or creating a reference to an object that persists across renders. Here's an example of how to use useRef to access a DOM element:
import React, { useRef } from 'react';
function MyComponent() {
const inputRef = useRef(null);
const handleClick = () => {
inputRef.current.focus();
};
return (
<div>
<input ref={inputRef} />
<button onClick={handleClick}>Focus Input</button>
</div>
);
}
In this example, we use the useRef hook to create a reference to the input element. We then use the reference to focus the input when the button is clicked.
useCallback
The useCallback hook allows you to memoize a function so that it is only re-created when its dependencies change. This can be useful for improving performance when passing functions as props to child components. Here's an example of how to use useCallback to memoize a click handler:
import React, { useCallback } from 'react';
function MyComponent() {
const handleClick = useCallback(() => {
console.log('Button clicked');
}, []);
return (
<div>
<button onClick={handleClick}>Click Me</button>
</div>
);
}
In this example, we use the useCallback hook to memoize the handleClick function. The second argument to useCallback is an array of dependencies that determine when the function should be re-created. In this case, we pass an empty array to indicate that the function should only be created once, when the component mounts.
useMemo
The useMemo hook allows you to memoize a value so that it is only re-computed when its dependencies change. This can be useful for improving performance when computing expensive values. Here's an example of how to use useMemo to compute the sum of an array:
import React, { useMemo } from 'react';
function MyComponent() {
const numbers = [1, 2, 3, 4, 5];
const sum = useMemo(() => {
console.log('Computing sum');
return numbers.reduce((acc, curr) => acc + curr, 0);
}, [numbers]);
return (
<div>
Sum: {sum}
</div>
);
}
In this example, we use the useMemo hook to memoize the sum of an array. The second argument to useMemo is an array of dependencies that determine when the value should be re-computed. In this case, we pass the numbers
array as a dependency, so the sum will only be re-computed when the array changes.
Conclusion
In this blog post, we explored how to use some of React's most powerful hooks: useEffect, useContext, useRef, useCallback, and useMemo. These hooks can help you manage state, consume context, access DOM elements, memoize functions, and memoize values in your React components. By using these hooks effectively, you can write more efficient, performant, and maintainable React code.
Also, if you enjoyed this content and would like to stay updated on future posts, feel free to connect with me on LinkedIn or X or check out my Github profile. I'll be sharing more tips and tricks on Django and other technologies, so don't miss out!
If you find my content valuable and would like to support me, you can also buy me a coffee. Your support helps me continue creating helpful and insightful content. Thank you!
Posted on March 16, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 6, 2024