3
Reading from Browser
Access window object and browser APIs safely in React
Intermediate
Core Concepts
- The
windowobject only exists in the browser, not on the server - Accessing
windowdirectly in your component will crash during server-side rendering - Use
useEffectto safely access browser APIs (it only runs in the browser) - Always clean up event listeners to prevent memory leaks
- Check
typeof window !== 'undefined'if you need to accesswindowoutsideuseEffect
Live Demo
Window Width
---px
How It Works
- 1Component mounts on the client
useEffectruns and readswindow.innerWidthsafely - 2Event listener is attached
window.addEventListener('resize', handleResize) - 3User resizes the browser window
The
resizeevent fires - 4
handleResizefunction runsUpdates
widthstate with new value - 5Component unmounts: cleanup runs
Event listener is removed to prevent leaks
Code
typescript
import { useState, useEffect } from 'react';
function WindowWidthTracker() {
const [width, setWidth] = useState(0);
useEffect(() => {
// Function to update width
const handleResize = () => {
setWidth(window.innerWidth);
};
// Set initial width
setWidth(window.innerWidth);
// Listen for window resize
window.addEventListener('resize', handleResize);
// CLEANUP: Remove listener when component unmounts
return () => {
window.removeEventListener('resize', handleResize);
};
}, []); // Empty array = only run once on mount
return (
<div>
<h1>Window Width: {width}px</h1>
<p>Resize your browser window!</p>
</div>
);
}import { useState, useEffect } from 'react';
function WindowWidthTracker() {
const [width, setWidth] = useState(0);
useEffect(() => {
// Function to update width
const handleResize = () => {
setWidth(window.innerWidth);
};
// Set initial width
setWidth(window.innerWidth);
// Listen for window resize
window.addEventListener('resize', handleResize);
// CLEANUP: Remove listener when component unmounts
return () => {
window.removeEventListener('resize', handleResize);
};
}, []); // Empty array = only run once on mount
return (
<div>
<h1>Window Width: {width}px</h1>
<p>Resize your browser window!</p>
</div>
);
}Common Browser APIs
window.innerWidth / innerHeight
Get viewport dimensions
window.scrollY
Get scroll position
localStorage / sessionStorage
Store data in browser
navigator.userAgent
Detect browser/device