What are controlled side effects?
Short answer: Controlled side effects refer to operations in React that happen as a result of state or props changes but are carefully managed, typically using React Hooks like useEffect.
Explain a bit more
Examples: Fetching data, subscribing to an event, manually updating the DOM, etc. Controlled: The side effect is triggered in response to specific state changes and cleaned up appropriately. Example of controlled side effect with useEffect: import React, { useState, useEffect } from 'react'; function MyComponent() { const [data, setData] = useState(null); useEffect(() => { const fetchData = async () => { const result = await fetch('/api/data'); const json = await result.json(); setData(json); }; fetchData(); }, []); // Only runs once when the component is mounted return <div>{data ? JSON.stringify(data) : 'Loading...'}</div>; } Here, useEffect handles the side effect of fetching data when the component mounts, and the state is updated with the fetched data.
Real-world example (ShopNest)
ShopNest’s storefront is React: components for ProductCard, CartDrawer, and CheckoutForm, with hooks for local UI state.
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