useEffect examples
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 the following sections, we are going to 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 Figure 5.6):
This can be done normally with a CSS media query, 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 = () => { const [width, setWidth] = useState(0) useEffect(() => { function handleResize() { setWidth(window.innerWidth) } ...