Consider a React app where UI, data fetching, and state management are all mixed in one component. What is the main benefit of separating these concerns into different components or hooks?
Think about how breaking tasks into smaller parts helps in real life, like organizing a kitchen by utensils, ingredients, and appliances.
Separating concerns means each part of the app handles one job well. This makes the code cleaner and easier to fix or update.
Given the following React components, what will be rendered on the screen?
function useCounter() { const [count, setCount] = React.useState(0); React.useEffect(() => { const timer = setInterval(() => setCount(c => c + 1), 1000); return () => clearInterval(timer); }, []); return count; } function CounterDisplay() { const count = useCounter(); return <div>Count: {count}</div>; }
Look at how useCounter updates state every second and returns the count.
The custom hook useCounter manages the count state and updates it every second. CounterDisplay uses this hook and shows the current count.
Choose the code snippet that properly separates data fetching logic from UI rendering using hooks.
Remember that data fetching should happen inside useEffect to avoid infinite loops and to handle async properly.
Option B uses a custom hook with useEffect to fetch data once and returns it. The component uses this hook and renders UI accordingly.
Examine the code below. What is the main problem related to separation of concerns?
function UserProfile() { const [user, setUser] = React.useState(null); React.useEffect(() => { fetch('/api/user').then(res => res.json()).then(setUser); }, []); function handleClick() { alert(`User: ${user.name}`); } return ( <div> <h1>{user ? user.name : 'Loading...'}</h1> <button onClick={handleClick}>Show Name</button> </div> ); }
Think about how separating data fetching, UI, and event logic into different parts helps clarity.
While the code works, combining fetching, UI, and event logic in one component violates separation of concerns, making future changes harder.
In a large React application, which approach best follows separation of concerns principles?
Think about dividing tasks like a team where each member has a clear role.
Custom hooks handle logic, presentational components focus on UI, and container components manage data flow. This clear separation improves maintainability and testing.