In class components, when updating the state based on the previous state, it's recommended to use a function rather than an object with `setState`. This avoids issues due to `setState` being asynchronous.
this.setState(prevState => ({
counter: prevState.counter + 1
}));
It's a common pattern, especially in the `componentDidUpdate` lifecycle method, to compare the current props with the previous ones to decide whether to perform an action.
componentDidUpdate(prevProps) {
if (this.props.id !== prevProps.id) {
fetchData(this.props.id);
}
}
In functional components, when using the `useReducer` hook, the reducer receives the current (or "previous") state as its first argument.
function counterReducer(prevState, action) {
switch (action.type) {
case 'INCREMENT':
return {count: prevState.count + 1};
default:
return prevState;
}
}
In functional components using the `useEffect` hook, you can access the previous state or props with the `useRef` hook.
function MyComponent(props) {
const prevPropsRef = useRef();
useEffect(() => {
if (prevPropsRef.current && props.value !== prevPropsRef.current.value) {
// Do something
}
prevPropsRef.current = props;
}, [props]);
}
Always remember to capture dependencies correctly when using hooks to prevent unintended behaviors.