Mid
From PDF
React
React.js
How do you handle side effects with hooks?
Short answer: Side effects are operations that occur outside of the React component’s scope, such as: Fetching data from an API Setting up subscriptions Manually modifying the DOM In React, side effects are handled using the useEffect hook. Basic
Example code
import React, { useState, useEffect } from 'react'; function Example() { const [count, setCount] = useState(0); useEffect(() => { document.title = `You clicked ${count} times`; }, [count]); // Only run when `count` changes return ( <div> <p>You clicked {count} times</p> <button onClick={() => setCount(count + 1)}>Click me</button> </div> ); } useEffect allows you to perform side effects in function components. The second argument, the dependency array, specifies when to run the effect. If the array is empty, the effect runs only once after the initial render (like componentDidMount).
Real-world example (ShopNest)
ShopNest’s cart icon uses useState for count and useEffect to load the cart once on mount.
Say this in the interview
- Define — one clear sentence (the short answer above).
- Example — relate it to a project like ShopNest or your real work.
- Trade-off — when you would not use it.
Share this Q&A
Share preview image: https://www.toolliyo.com/images/toolliyo-logo.png