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

  1. Define — one clear sentence (the short answer above).
  2. Example — relate it to a project like ShopNest or your real work.
  3. Trade-off — when you would not use it.
Toolliyo Assistant
Ask about tutorials, ebooks, training, pricing, mentor services, and support. I use public site content only—not admin or internal tools.

care@toolliyo.com

Need callback? Share your details