'Synchronizing with Effects'·续2
Sending analytics
Consider this code that sends an analytics event on the page visit:
useEffect(() => {
logVisit(url); // Sends a POST request
}, [url]);
In development, logVisit will be called twice for every URL, so you might be tempted to try to fix that. We recommend keeping this code as is. Like with earlier examples, there is no user-visible behavior difference between running it once and running it twice. From a practical point of view, logVisit should not do anything in development because you don't want the logs from the development machines to skew the production metrics. Your component remounts every time you save its file, so it logs extra visits in development anyway.
In production, there will be no duplicate visit logs.
To debug the analytics events you're sending, you can deploy your app to a staging environment (which runs in production mode) or temporarily opt out of Strict Mode and its development-only remounting checks. You may also send analytics from the route change event handlers instead of Effects. For more precise analytics, intersection observers can help track which components are in the viewport and how long they remain visible.
Not an Effect: Initializing the application
Some logic should only run once when the application starts. You can put it outside your components:
```js {2-3} if (typeof window !== 'undefined') { // Check if we're running in the browser. checkAuthToken(); loadDataFromLocalStorage(); }
function App() { // ... }
This guarantees that such logic only runs once after the browser loads the page.
### Not an Effect: Buying a product
Sometimes, even if you write a cleanup function, there's no way to prevent user-visible consequences of running the Effect twice. For example, maybe your Effect sends a POST request like buying a product:
```js {2-3}
useEffect(() => {
// 🔴 Wrong: This Effect fires twice in development, exposing a problem in the code.
fetch('/api/buy', { method: 'POST' });
}, []);
You wouldn't want to buy the product twice. However, this is also why you shouldn't put this logic in an Effect. What if the user goes to another page and then presses Back? Your Effect would run again. You don't want to buy the product when the user visits a page; you want to buy it when the user clicks the Buy button.
Buying is not caused by rendering; it's caused by a specific interaction. It should run only when the user presses the button. Delete the Effect and move your /api/buy request into the Buy button event handler:
```js {2-3} function handleClick() { // ✅ Buying is an event because it is caused by a particular interaction. fetch('/api/buy', { method: 'POST' }); }
**This illustrates that if remounting breaks the logic of your application, this usually uncovers existing bugs.** From a user's perspective, visiting a page shouldn't be different from visiting it, clicking a link, then pressing Back to view the page again. React verifies that your components abide by this principle by remounting them once in development.
## Putting it all together
This playground can help you "get a feel" for how Effects work in practice.
This example uses [`setTimeout`](https://developer.mozilla.org/en-US/docs/Web/API/setTimeout) to schedule a console log with the input text to appear three seconds after the Effect runs. The cleanup function cancels the pending timeout. Start by pressing "Mount the component":
```js
import { useState, useEffect } from 'react';
function Playground() {
const [text, setText] = useState('a');
useEffect(() => {
function onTimeout() {
console.log('⏰ ' + text);
}
console.log('🔵 Schedule "' + text + '" log');
const timeoutId = setTimeout(onTimeout, 3000);
return () => {
console.log('🟡 Cancel "' + text + '" log');
clearTimeout(timeoutId);
};
}, [text]);
return (
<>
<label>
What to log:{' '}
<input
value={text}
onChange={e => setText(e.target.value)}
/>
</label>
<h1>{text}</h1>
</>
);
}
export default function App() {
const [show, setShow] = useState(false);
return (
<>
<button onClick={() => setShow(!show)}>
{show ? 'Unmount' : 'Mount'} the component
</button>
{show && <hr />}
{show && <Playground />}
</>
);
}
You will see three logs at first: Schedule "a" log, Cancel "a" log, and Schedule "a" log again. Three second later there will also be a log saying a. As you learned earlier, the extra schedule/cancel pair is because React remounts the component once in development to verify that you've implemented cleanup well.
Now edit the input to say abc. If you do it fast enough, you'll see Schedule "ab" log immediately followed by Cancel "ab" log and Schedule "abc" log. React always cleans up the previous render's Effect before the next render's Effect. This is why even if you type into the input fast, there is at most one timeout scheduled at a time. Edit the input a few times and watch the console to get a feel for how Effects get cleaned up.
Type something into the input and then immediately press "Unmount the component". Notice how unmounting cleans up the last render's Effect. Here, it clears the last timeout before it has a chance to fire.
Finally, edit the component above and comment out the cleanup function so that the timeouts don't get cancelled. Try typing abcde fast. What do you expect to happen in three seconds? Will console.log(text) inside the timeout print the latest text and produce five abcde logs? Give it a try to check your intuition!
Three seconds later, you should see a sequence of logs (a, ab, abc, abcd, and abcde) rather than five abcde logs. Each Effect "captures" the text value from its corresponding render. It doesn't matter that the text state changed: an Effect from the render with text = 'ab' will always see 'ab'. In other words, Effects from each render are isolated from each other. If you're curious how this works, you can read about closures.
[!INFO]
Each render has its own Effects
You can think of
useEffectas "attaching" a piece of behavior to the render output. Consider this Effect:
export default function ChatRoom({ roomId }) {
useEffect(() => {
const connection = createConnection(roomId);
connection.connect();
return () => connection.disconnect();
}, [roomId]);
return <h1>Welcome to {roomId}!</h1>;
}
Let's see what exactly happens as the user navigates around the app.
Initial render
The user visits
<ChatRoom roomId="general" />. Let's mentally substituteroomIdwith'general':
// JSX for the first render (roomId = "general")
return <h1>Welcome to general!</h1>;
The Effect is also a part of the rendering output. The first render's Effect becomes:
// Effect for the first render (roomId = "general")
() => {
const connection = createConnection('general');
connection.connect();
return () => connection.disconnect();
},
// Dependencies for the first render (roomId = "general")
['general']
React runs this Effect, which connects to the
'general'chat room.Re-render with same dependencies
Let's say
<ChatRoom roomId="general" />re-renders. The JSX output is the same:
// JSX for the second render (roomId = "general")
return <h1>Welcome to general!</h1>;
React sees that the rendering output has not changed, so it doesn't update the DOM.
The Effect from the second render looks like this:
// Effect for the second render (roomId = "general")
() => {
const connection = createConnection('general');
connection.connect();
return () => connection.disconnect();
},
// Dependencies for the second render (roomId = "general")
['general']
React compares
['general']from the second render with['general']from the first render. Because all dependencies are the same, React ignores the Effect from the second render. It never gets called.Re-render with different dependencies
Then, the user visits
<ChatRoom roomId="travel" />. This time, the component returns different JSX:
// JSX for the third render (roomId = "travel")
return <h1>Welcome to travel!</h1>;
React updates the DOM to change
"Welcome to general"into"Welcome to travel".The Effect from the third render looks like this:
// Effect for the third render (roomId = "travel")
() => {
const connection = createConnection('travel');
connection.connect();
return () => connection.disconnect();
},
// Dependencies for the third render (roomId = "travel")
['travel']
React compares
['travel']from the third render with['general']from the second render. One dependency is different:Object.is('travel', 'general')isfalse. The Effect can't be skipped.Before React can apply the Effect from the third render, it needs to clean up the last Effect that did run. The second render's Effect was skipped, so React needs to clean up the first render's Effect. If you scroll up to the first render, you'll see that its cleanup calls
disconnect()on the connection that was created withcreateConnection('general'). This disconnects the app from the'general'chat room.After that, React runs the third render's Effect. It connects to the
'travel'chat room.Unmount
Finally, let's say the user navigates away, and the
ChatRoomcomponent unmounts. React runs the last Effect's cleanup function. The last Effect was from the third render. The third render's cleanup destroys thecreateConnection('travel')connection. So the app disconnects from the'travel'room.Development-only behaviors
When Strict Mode is on, React remounts every component once after mount (state and DOM are preserved). This helps you find Effects that need cleanup and exposes bugs like race conditions early. Additionally, React will remount the Effects whenever you save a file in development. Both of these behaviors are development-only.
- Unlike events, Effects are caused by rendering itself rather than a particular interaction.
- Effects let you synchronize a component with some external system (third-party API, network, etc).
- By default, Effects run after every render (including the initial one).
- React will skip the Effect if all of its dependencies have the same values as during the last render.
- You can't "choose" your dependencies. They are determined by the code inside the Effect.
- Empty dependency array (
[]) corresponds to the component "mounting", i.e. being added to the screen. - In Strict Mode, React mounts components twice (in development only!) to stress-test your Effects.
- If your Effect breaks because of remounting, you need to implement a cleanup function.
- React will call your cleanup function before the Effect runs next time, and during the unmount.
Focus a field on mount
In this example, the form renders a <MyInput /> component.
Use the input's focus() method to make MyInput automatically focus when it appears on the screen. There is already a commented out implementation, but it doesn't quite work. Figure out why it doesn't work, and fix it. (If you're familiar with the autoFocus attribute, pretend that it does not exist: we are reimplementing the same functionality from scratch.)
```js src/MyInput.js active import { useEffect, useRef } from 'react';
export default function MyInput({ value, onChange }) { const ref = useRef(null);
// TODO: This doesn't quite work. Fix it. // ref.current.focus()
return ( ); }
```js src/App.js hidden
import { useState } from 'react';
import MyInput from './MyInput.js';
export default function Form() {
const [show, setShow] = useState(false);
const [name, setName] = useState('Taylor');
const [upper, setUpper] = useState(false);
return (
<>
<button onClick={() => setShow(s => !s)}>{show ? 'Hide' : 'Show'} form</button>
<br />
<hr />
{show && (
<>
<label>
Enter your name:
<MyInput
value={name}
onChange={e => setName(e.target.value)}
/>
</label>
<label>
<input
type="checkbox"
checked={upper}
onChange={e => setUpper(e.target.checked)}
/>
Make it uppercase
</label>
<p>Hello, <b>{upper ? name.toUpperCase() : name}</b></p>
</>
)}
</>
);
}
label {
display: block;
margin-top: 20px;
margin-bottom: 20px;
}
body {
min-height: 150px;
}
To verify that your solution works, press "Show form" and verify that the input receives focus (becomes highlighted and the cursor is placed inside). Press "Hide form" and "Show form" again. Verify the input is highlighted again.
MyInput should only focus on mount rather than after every render. To verify that the behavior is right, press "Show form" and then repeatedly press the "Make it uppercase" checkbox. Clicking the checkbox should not focus the input above it.
Calling ref.current.focus() during render is wrong because it is a side effect. Side effects should either be placed inside an event handler or be declared with useEffect. In this case, the side effect is caused by the component appearing rather than by any specific interaction, so it makes sense to put it in an Effect.
To fix the mistake, wrap the ref.current.focus() call into an Effect declaration. Then, to ensure that this Effect runs only on mount rather than after every render, add the empty [] dependencies to it.
```js src/MyInput.js active import { useEffect, useRef } from 'react';
export default function MyInput({ value, onChange }) { const ref = useRef(null);
useEffect(() => { ref.current.focus(); }, []);
return ( ); }
```js src/App.js hidden
import { useState } from 'react';
import MyInput from './MyInput.js';
export default function Form() {
const [show, setShow] = useState(false);
const [name, setName] = useState('Taylor');
const [upper, setUpper] = useState(false);
return (
<>
<button onClick={() => setShow(s => !s)}>{show ? 'Hide' : 'Show'} form</button>
<br />
<hr />
{show && (
<>
<label>
Enter your name:
<MyInput
value={name}
onChange={e => setName(e.target.value)}
/>
</label>
<label>
<input
type="checkbox"
checked={upper}
onChange={e => setUpper(e.target.checked)}
/>
Make it uppercase
</label>
<p>Hello, <b>{upper ? name.toUpperCase() : name}</b></p>
</>
)}
</>
);
}
