Skip to content

Commit

Permalink
Add stable fn notes to useMemo, useTransition, useState, and useReduc…
Browse files Browse the repository at this point in the history
…er (#7181)
  • Loading branch information
rickhanlonii authored Sep 22, 2024
1 parent 39abc60 commit c003ac4
Show file tree
Hide file tree
Showing 5 changed files with 86 additions and 4 deletions.
8 changes: 4 additions & 4 deletions src/content/reference/react/useCallback.md
Original file line number Diff line number Diff line change
Expand Up @@ -711,7 +711,7 @@ function ChatRoom({ roomId }) {

useEffect(() => {
const options = createOptions();
const connection = createConnection();
const connection = createConnection(options);
connection.connect();
// ...
```
Expand All @@ -722,7 +722,7 @@ This creates a problem. [Every reactive value must be declared as a dependency o
```js {6}
useEffect(() => {
const options = createOptions();
const connection = createConnection();
const connection = createConnection(options);
connection.connect();
return () => connection.disconnect();
}, [createOptions]); // 🔴 Problem: This dependency changes on every render
Expand All @@ -744,7 +744,7 @@ function ChatRoom({ roomId }) {

useEffect(() => {
const options = createOptions();
const connection = createConnection();
const connection = createConnection(options);
connection.connect();
return () => connection.disconnect();
}, [createOptions]); // ✅ Only changes when createOptions changes
Expand All @@ -766,7 +766,7 @@ function ChatRoom({ roomId }) {
}

const options = createOptions();
const connection = createConnection();
const connection = createConnection(options);
connection.connect();
return () => connection.disconnect();
}, [roomId]); // ✅ Only changes when roomId changes
Expand Down
77 changes: 77 additions & 0 deletions src/content/reference/react/useMemo.md
Original file line number Diff line number Diff line change
Expand Up @@ -1056,6 +1056,83 @@ Keep in mind that you need to run React in production mode, disable [React Devel

---

### Preventing an Effect from firing too often {/*preventing-an-effect-from-firing-too-often*/}

Sometimes, you might want to use a value inside an [Effect:](/learn/synchronizing-with-effects)

```js {4-7,10}
function ChatRoom({ roomId }) {
const [message, setMessage] = useState('');

const options = {
serverUrl: 'https://localhost:1234',
roomId: roomId
}

useEffect(() => {
const connection = createConnection(options);
connection.connect();
// ...
```
This creates a problem. [Every reactive value must be declared as a dependency of your Effect.](/learn/lifecycle-of-reactive-effects#react-verifies-that-you-specified-every-reactive-value-as-a-dependency) However, if you declare `options` as a dependency, it will cause your Effect to constantly reconnect to the chat room:
```js {5}
useEffect(() => {
const connection = createConnection(options);
connection.connect();
return () => connection.disconnect();
}, [options]); // 🔴 Problem: This dependency changes on every render
// ...
```
To solve this, you can wrap the object you need to call from an Effect in `useMemo`:
```js {4-9,16}
function ChatRoom({ roomId }) {
const [message, setMessage] = useState('');

const options = useMemo(() => {
return {
serverUrl: 'https://localhost:1234',
roomId: roomId
};
}, [roomId]); // ✅ Only changes when roomId changes

useEffect(() => {
const options = createOptions();
const connection = createConnection(options);
connection.connect();
return () => connection.disconnect();
}, [options]); // ✅ Only changes when createOptions changes
// ...
```
This ensures that the `options` object is the same between re-renders if `useMemo` returns the cached object.
However, since `useMemo` is performance optimization, not a semantic guarantee, React may throw away the cached value if [there is a specific reason to do that](#caveats). This will also cause the effect to re-fire, **so it's even better to remove the need for a function dependency** by moving your object *inside* the Effect:
```js {5-8,13}
function ChatRoom({ roomId }) {
const [message, setMessage] = useState('');

useEffect(() => {
const options = { // ✅ No need for useMemo or object dependencies!
serverUrl: 'https://localhost:1234',
roomId: roomId
}

const connection = createConnection(options);
connection.connect();
return () => connection.disconnect();
}, [roomId]); // ✅ Only changes when roomId changes
// ...
```
Now your code is simpler and doesn't need `useMemo`. [Learn more about removing Effect dependencies.](/learn/removing-effect-dependencies#move-dynamic-objects-and-functions-inside-your-effect)
### Memoizing a dependency of another Hook {/*memoizing-a-dependency-of-another-hook*/}
Suppose you have a calculation that depends on an object created directly in the component body:
Expand Down
1 change: 1 addition & 0 deletions src/content/reference/react/useReducer.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ function MyComponent() {
#### Caveats {/*caveats*/}
* `useReducer` is a Hook, so you can only call it **at the top level of your component** or your own Hooks. You can't call it inside loops or conditions. If you need that, extract a new component and move the state into it.
* The `dispatch` function has a stable identity, so you will often see it omitted from effect dependencies, but including it will not cause the effect to fire. If the linter lets you omit a dependency without errors, it is safe to do. [Learn more about removing Effect dependencies.](/learn/removing-effect-dependencies#move-dynamic-objects-and-functions-inside-your-effect)
* In Strict Mode, React will **call your reducer and initializer twice** in order to [help you find accidental impurities.](#my-reducer-or-initializer-function-runs-twice) This is development-only behavior and does not affect production. If your reducer and initializer are pure (as they should be), this should not affect your logic. The result from one of the calls is ignored.
---
Expand Down
2 changes: 2 additions & 0 deletions src/content/reference/react/useState.md
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,8 @@ function handleClick() {
* React [batches state updates.](/learn/queueing-a-series-of-state-updates) It updates the screen **after all the event handlers have run** and have called their `set` functions. This prevents multiple re-renders during a single event. In the rare case that you need to force React to update the screen earlier, for example to access the DOM, you can use [`flushSync`.](/reference/react-dom/flushSync)
* The `set` function has a stable identity, so you will often see it omitted from effect dependencies, but including it will not cause the effect to fire. If the linter lets you omit a dependency without errors, it is safe to do. [Learn more about removing Effect dependencies.](/learn/removing-effect-dependencies#move-dynamic-objects-and-functions-inside-your-effect)
* Calling the `set` function *during rendering* is only allowed from within the currently rendering component. React will discard its output and immediately attempt to render it again with the new state. This pattern is rarely needed, but you can use it to **store information from the previous renders**. [See an example below.](#storing-information-from-previous-renders)
* In Strict Mode, React will **call your updater function twice** in order to [help you find accidental impurities.](#my-initializer-or-updater-function-runs-twice) This is development-only behavior and does not affect production. If your updater function is pure (as it should be), this should not affect the behavior. The result from one of the calls will be ignored.
Expand Down
2 changes: 2 additions & 0 deletions src/content/reference/react/useTransition.md
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,8 @@ function TabContainer() {

* The function you pass to `startTransition` must be synchronous. React immediately executes this function, marking all state updates that happen while it executes as Transitions. If you try to perform more state updates later (for example, in a timeout), they won't be marked as Transitions.

* The `startTransition` function has a stable identity, so you will often see it omitted from effect dependencies, but including it will not cause the effect to fire. If the linter lets you omit a dependency without errors, it is safe to do. [Learn more about removing Effect dependencies.](/learn/removing-effect-dependencies#move-dynamic-objects-and-functions-inside-your-effect)

* A state update marked as a Transition will be interrupted by other state updates. For example, if you update a chart component inside a Transition, but then start typing into an input while the chart is in the middle of a re-render, React will restart the rendering work on the chart component after handling the input update.

* Transition updates can't be used to control text inputs.
Expand Down

0 comments on commit c003ac4

Please sign in to comment.