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):
This can be done normally with a
const Greeting = () => {// State variable 'width' and its corresponding updater function 'setWidth'const [width, setWidth] = useState(0);// Effect to update 'width' when window is resizeduseEffect(() => {function handleResize() {setWidth(window.innerWidth);}// Add event listener for 'resize' event and initial resize handlingwindow.addEventListener("resize", handleResize);handleResize();// Cleanup function to remove event listener when component unmountsreturn () => {window.removeEventListener("resize", handleResize);};}, [setWidth]); // Dependency array includes 'setWidth', as it's used in the effect// Determine if 'width' is greater than 600const on = width > 600;// This component renders an h1 element displaying different messages based on the 'on' conditionreturn <h1>{on ? "Hello World" : "Hello"}</h1>;};
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 ...