Sub topic 3
Avoid Chains of Effects That Trigger Each Other
Assume you know function components, JSX, props, useState, and the basic useEffect dependency array. An Effect runs after rendering to synchronize React with something outside React. It should not be a pipeline for moving data between React state variables.
Avoid Effect chains
If one Effect sets state and another Effect watches that state, a single user action can cause several render passes. Put the related updates in the event handler instead.
flowchart TD
A[User action] --> B[Event handler]
B --> C[Update related state together]
C --> D[One render]
D --> E[External synchronization Effect, if needed]For example, selecting an item might update both selectedId and detailsVisible. The click handler can update both values. Do not set selectedId in the handler and then use an Effect to set detailsVisible.
Notify parents from the event
A child should notify its parent in the same event that changes its local state. An Effect that watches local state tells the parent one render later and can create an avoidable extra render.
function Toggle({ onChange }) {
const [isOn, setIsOn] = useState(false);
function handleClick() {
const next = !isOn;
setIsOn(next);
onChange(next);
}
return <button onClick={handleClick}>{isOn ? 'On' : 'Off'}</button>;
}Subscribe to external stores
For browser or third-party data that changes outside React, use useSyncExternalStore. It connects a subscription to rendering without copying the external value into state.
import { useSyncExternalStore } from 'react';
function subscribe(callback) {
addEventListener('online', callback);
addEventListener('offline', callback);
return () => {
removeEventListener('online', callback);
removeEventListener('offline', callback);
};
}
export function useOnlineStatus() {
return useSyncExternalStore(subscribe, () => navigator.onLine, () => true);
}Initialize the app once
Application-wide initialization, such as configuring a library, belongs at module scope or in the application entry point. This makes its one-time nature clear. Do not add an Effect solely to run setup after the first render.
When an Effect is appropriate
Fetching data because a component is displayed is synchronization with the network. Include the query in the dependency list and ignore stale responses during cleanup.
useEffect(() => {
let ignore = false;
fetch('/api/search?q=' + encodeURIComponent(query))
.then(response => response.json())
.then(data => {
if (!ignore) setResults(data);
});
return () => {
ignore = true;
};
}, [query]);Exercise
Where should code that happens because the user clicked a button usually go?
Show answer
In the event handler, where the action and its related state updates can be handled together.