// Avoid
const [fullName, setFullName] = useState('');
useEffect(() => {
setFullName(firstName + ' ' + lastName);
}, [firstName, lastName]);
// Prefer
const fullName = firstName + ' ' + lastName;
You do not need an effect when no external system is involved. Effects are for synchronizing with systems outside React, such as the network, browser APIs, timers or third-party widgets.
Derived data is the most common case. Don't store fullName in state and update it in an effect when firstName changes. Compute it during render instead. Wrap it in useMemo only if the calculation is expensive. Effects that sync state cause an extra render, and the first render shows stale values.
Other effects you can remove:
- Logic caused by a specific user action, like sending a POST when a button is clicked. Put it in the event handler.
- Resetting all state when a prop changes. Use a
keyinstead. - Notifying a parent of a change. Do it in the same handler that changed the state.
- Effects are for syncing with external systems.
- Compute derived values during render instead of syncing them into state.
- Use
useMemofor expensive derived calculations. - Put logic triggered by user actions in event handlers.
- Reset state with a
keyinstead of an effect.