You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Sometimes, you need previous props to **clean up an effect.** For example, you might have an effect that subscribes to a socket based on the `userId` prop. If the `userId` prop changes, you want to unsubscribe from the _previous_`userId` and subscribe to the _next_ one. You don't need to do anything special for this to work:
Note how this would work for props, state, or any other calculated value.
369
-
370
-
```js{5}
371
-
function Counter() {
372
-
const [count, setCount] = useState(0);
373
-
374
-
const calculation = count + 100;
375
-
const prevCalculation = usePrevious(calculation);
376
-
// ...
377
-
```
345
+
In the above example, if `userId` changes from `3` to `4`, `ChatAPI.unsubscribeFromSocket(3)` will run first, and then `ChatAPI.subscribeToSocket(4)` will run. There is no need to get "previous" `userId` because the cleanup function will capture it in a closure.
378
346
379
-
It's possible that in the future React will provide a `usePrevious` Hook out of the box since it's a relatively common use case.
347
+
Other times, you might need to **adjust state based on a change in props or other state**. This is rarely needed and is usually a sign you have some duplicate or redundant state. However, in the rare case that you need this pattern, you can [store previous state or props in state and update them during rendering](#how-do-i-implement-getderivedstatefromprops).
380
348
381
-
See also [the recommended pattern for derived state](#how-do-i-implement-getderivedstatefromprops).
349
+
We have previously suggested a custom Hook called `usePrevious` to hold the previous value. However, we've found that most use cases fall into the two patterns described above. If your use case is different, you can [hold a value in a ref](#is-there-something-like-instance-variables) and manually update it when needed. Avoid reading and updating refs during rendering because this makes your component's behavior difficult to predict and understand.
382
350
383
351
### Why am I seeing stale props or state inside my function? {#why-am-i-seeing-stale-props-or-state-inside-my-function}
0 commit comments