...

/

The useEffect Hook Examples

The useEffect Hook Examples

Learn about two practical examples of using the useEffect hook in React: finding the window size dynamically and fetching an API resource.

The useEffect hook is normally used for any side effect—whether that is to read from an external object or write to an external object. In this lesson, we'll see two more examples: finding the window size and fetching an API resource.

Finding the window size

Let's say that we want to know the current browser window size at runtime so that a greeting title can fit perfectly onto the screen (see the image below):

Press + to interact
Finding the window size
Finding the window size

This can be done normally with a CSS media query CSS media queries are a feature that allows web developers to apply different styles to a webpage based on specific conditions, such as the characteristics of the device or screen size. This enables the creation of responsive designs that adapt to various devices, ensuring a consistent and user-friendly experience. , but this time, we want to do it via JavaScript, as a runtime JavaScript variable obtained can be sent for purposes other than CSS usage:

const Greeting = () => {
// State variable 'width' and its corresponding updater function 'setWidth'
const [width, setWidth] = useState(0);
// Effect to update 'width' when window is resized
useEffect(() => {
function handleResize() {
setWidth(window.innerWidth);
}
// Add event listener for 'resize' event and initial resize handling
window.addEventListener("resize", handleResize);
handleResize();
// Cleanup function to remove event listener when component unmounts
return () => {
window.removeEventListener("resize", handleResize);
};
}, [setWidth]); // Dependency array includes 'setWidth', as it's used in the effect
// Determine if 'width' is greater than 600
const on = width > 600;
// This component renders an h1 element displaying different messages based on the 'on' condition
return <h1>{on ? "Hello World" : "Hello"}</h1>;
};
React component 'Greeting' dynamically updating based on window width

The useEffect hook is a good fit here. After the component is mounted, we can listen for a resize event provided by the window object. Once it starts to listen to the event, every time the window resizes, it kicks off a handleResize function that sets the width state to the new window size. We also invoke handleResize at the mount to get the initial window size.

In this example, if the current width is greater than 600 px, we know that it can fit the Hello World string on the screen. Otherwise, the Hello string will be used. This shows that we can control the ...