<StrictMode>·续
return <h1>Welcome to the {roomId} room!</h1>; }
export default function App() { const [roomId, setRoomId] = useState('general'); const [show, setShow] = useState(false); return ( <> <label> Choose the chat room:{' '} <select value={roomId} onChange={e => setRoomId(e.target.value)} > <option value="general">general</option> <option value="travel">travel</option> <option value="music">music</option> </select> </label> <button onClick={() => setShow(!show)}> {show ? 'Close chat' : 'Open chat'} </button> {show && <hr />} {show && <ChatRoom roomId={roomId} />} </> ); }
```js src/chat.js
let connections = 0;
export function createConnection(serverUrl, roomId) {
// A real implementation would actually connect to the server
return {
connect() {
console.log('✅ Connecting to "' + roomId + '" room at ' + serverUrl + '...');
connections++;
console.log('Active connections: ' + connections);
},
disconnect() {
console.log('❌ Disconnected from "' + roomId + '" room at ' + serverUrl);
connections--;
console.log('Active connections: ' + connections);
}
};
}
input { display: block; margin-bottom: 20px; }
button { margin-left: 10px; }
You'll notice that the number of open connections always keeps growing. In a real app, this would cause performance and network problems. The issue is that your Effect is missing a cleanup function:
```js {4} useEffect(() => { const connection = createConnection(serverUrl, roomId); connection.connect(); return () => connection.disconnect(); }, [roomId]);
Now that your Effect "cleans up" after itself and destroys the outdated connections, the leak is solved. However, notice that the problem did not become visible until you've added more features (the select box).
**In the original example, the bug wasn't obvious. Now let's wrap the original (buggy) code in `<StrictMode>`:**
```js src/index.js
import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import './styles.css';
import App from './App';
const root = createRoot(document.getElementById("root"));
root.render(
<StrictMode>
<App />
</StrictMode>
);
import { useState, useEffect } from 'react';
import { createConnection } from './chat.js';
const serverUrl = 'https://localhost:1234';
const roomId = 'general';
export default function ChatRoom() {
useEffect(() => {
const connection = createConnection(serverUrl, roomId);
connection.connect();
}, []);
return <h1>Welcome to the {roomId} room!</h1>;
}
```js src/chat.js let connections = 0;
export function createConnection(serverUrl, roomId) { // A real implementation would actually connect to the server return { connect() { console.log('✅ Connecting to "' + roomId + '" room at ' + serverUrl + '...'); connections++; console.log('Active connections: ' + connections); }, disconnect() { console.log('❌ Disconnected from "' + roomId + '" room at ' + serverUrl); connections--; console.log('Active connections: ' + connections); } }; }
```css
input { display: block; margin-bottom: 20px; }
button { margin-left: 10px; }
With Strict Mode, you immediately see that there is a problem (the number of active connections jumps to 2). Strict Mode runs an extra setup+cleanup cycle for every Effect. This Effect has no cleanup logic, so it creates an extra connection but doesn't destroy it. This is a hint that you're missing a cleanup function.
Strict Mode lets you notice such mistakes early in the process. When you fix your Effect by adding a cleanup function in Strict Mode, you also fix many possible future production bugs like the select box from before:
```js src/index.js import { StrictMode } from 'react'; import { createRoot } from 'react-dom/client'; import './styles.css';
import App from './App';
const root = createRoot(document.getElementById("root")); root.render( <StrictMode> <App /> </StrictMode> );
```js
import { useState, useEffect } from 'react';
import { createConnection } from './chat.js';
const serverUrl = 'https://localhost:1234';
function ChatRoom({ roomId }) {
useEffect(() => {
const connection = createConnection(serverUrl, roomId);
connection.connect();
return () => connection.disconnect();
}, [roomId]);
return <h1>Welcome to the {roomId} room!</h1>;
}
export default function App() {
const [roomId, setRoomId] = useState('general');
const [show, setShow] = useState(false);
return (
<>
<label>
Choose the chat room:{' '}
<select
value={roomId}
onChange={e => setRoomId(e.target.value)}
>
<option value="general">general</option>
<option value="travel">travel</option>
<option value="music">music</option>
</select>
</label>
<button onClick={() => setShow(!show)}>
{show ? 'Close chat' : 'Open chat'}
</button>
{show && <hr />}
{show && <ChatRoom roomId={roomId} />}
</>
);
}
```js src/chat.js let connections = 0;
export function createConnection(serverUrl, roomId) { // A real implementation would actually connect to the server return { connect() { console.log('✅ Connecting to "' + roomId + '" room at ' + serverUrl + '...'); connections++; console.log('Active connections: ' + connections); }, disconnect() { console.log('❌ Disconnected from "' + roomId + '" room at ' + serverUrl); connections--; console.log('Active connections: ' + connections); } }; }
```css
input { display: block; margin-bottom: 20px; }
button { margin-left: 10px; }
Notice how the active connection count in the console doesn't keep growing anymore.
Without Strict Mode, it was easy to miss that your Effect needed cleanup. By running setup → cleanup → setup instead of setup for your Effect in development, Strict Mode made the missing cleanup logic more noticeable.
Read more about implementing Effect cleanup.
Fixing bugs found by re-running ref callbacks in development
Strict Mode can also help find bugs in callbacks refs.
Every callback ref has some setup code and may have some cleanup code. Normally, React calls setup when the element is created (is added to the DOM) and calls cleanup when the element is removed (is removed from the DOM).
When Strict Mode is on, React will also run one extra setup+cleanup cycle in development for every callback ref. This may feel surprising, but it helps reveal subtle bugs that are hard to catch manually.
Consider this example, which allows you to select an animal and then scroll to one of them. Notice when you switch from "Cats" to "Dogs", the console logs show that the number of animals in the list keeps growing, and the "Scroll to" buttons stop working:
```js src/index.js import { createRoot } from 'react-dom/client'; import './styles.css';
import App from './App';
const root = createRoot(document.getElementById("root")); // ❌ Not using StrictMode. root.render(<App />);
```js src/App.js active
import { useRef, useState } from "react";
export default function CatFriends() {
const itemsRef = useRef([]);
const [catList, setCatList] = useState(setupCatList);
const [cat, setCat] = useState('neo');
function scrollToCat(index) {
const list = itemsRef.current;
const {node} = list[index];
node.scrollIntoView({
behavior: "smooth",
block: "nearest",
inline: "center",
});
}
const cats = catList.filter(c => c.type === cat)
return (
<>
<nav>
<button onClick={() => setCat('neo')}>Neo</button>
<button onClick={() => setCat('millie')}>Millie</button>
</nav>
<hr />
<nav>
<span>Scroll to:</span>{cats.map((cat, index) => (
<button key={cat.src} onClick={() => scrollToCat(index)}>
{index}
</button>
))}
</nav>
<div>
<ul>
{cats.map((cat) => (
<li
key={cat.src}
ref={(node) => {
const list = itemsRef.current;
const item = {cat: cat, node};
list.push(item);
console.log(`✅ Adding cat to the map. Total cats: ${list.length}`);
if (list.length > 10) {
console.log('❌ Too many cats in the list!');
}
return () => {
// 🚩 No cleanup, this is a bug!
}
}}
>
<img src={cat.src} />
</li>
))}
</ul>
</div>
</>
);
}
function setupCatList() {
const catList = [];
for (let i = 0; i < 10; i++) {
catList.push({type: 'neo', src: "https://placecats.com/neo/320/240?" + i});
}
for (let i = 0; i < 10; i++) {
catList.push({type: 'millie', src: "https://placecats.com/millie/320/240?" + i});
}
return catList;
}
div {
width: 100%;
overflow: hidden;
}
nav {
text-align: center;
}
button {
margin: .25rem;
}
ul,
li {
list-style: none;
white-space: nowrap;
}
li {
display: inline;
padding: 0.5rem;
}
This is a production bug! Since the ref callback doesn't remove animals from the list in the cleanup, the list of animals keeps growing. This is a memory leak that can cause performance problems in a real app, and breaks the behavior of the app.
The issue is the ref callback doesn't cleanup after itself:
```js {6-8} <li ref={node => { const list = itemsRef.current; const item = {animal, node}; list.push(item); return () => { // 🚩 No cleanup, this is a bug! } }} </li>
Now let's wrap the original (buggy) code in `<StrictMode>`:
```js src/index.js
import { createRoot } from 'react-dom/client';
import {StrictMode} from 'react';
import './styles.css';
import App from './App';
const root = createRoot(document.getElementById("root"));
// ✅ Using StrictMode.
root.render(
<StrictMode>
<App />
</StrictMode>
);
```js src/App.js active import { useRef, useState } from "react";
export default function CatFriends() { const itemsRef = useRef([]); const [catList, setCatList] = useState(setupCatList); const [cat, setCat] = useState('neo');
function scrollToCat(index) { const list = itemsRef.current; const {node} = list[index]; node.scrollIntoView({ behavior: "smooth", block: "nearest", inline: "center", }); }
const cats = catList.filter(c => c.type === cat)
return (
<>
<nav>
<button onClick={() => setCat('neo')}>Neo</button>
<button onClick={() => setCat('millie')}>Millie</button>
</nav>
<hr />
<nav>
<span>Scroll to:</span>{cats.map((cat, index) => (
<button key={cat.src} onClick={() => scrollToCat(index)}>
{index}
</button>
))}
</nav>
<div>
<ul>
{cats.map((cat) => (
<li
key={cat.src}
ref={(node) => {
const list = itemsRef.current;
const item = {cat: cat, node};
list.push(item);
console.log(✅ Adding cat to the map. Total cats: ${list.length});
if (list.length > 10) {
console.log('❌ Too many cats in the list!');
}
return () => {
// 🚩 No cleanup, this is a bug!
}
}}
>
<img src={cat.src} />
</li>
))}
</ul>
</div>
</>
);
}
function setupCatList() { const catList = []; for (let i = 0; i < 10; i++) { catList.push({type: 'neo', src: "https://placecats.com/neo/320/240?" + i}); } for (let i = 0; i < 10; i++) { catList.push({type: 'millie', src: "https://placecats.com/millie/320/240?" + i}); }
return catList; }
```css
div {
width: 100%;
overflow: hidden;
}
nav {
text-align: center;
}
button {
margin: .25rem;
}
ul,
li {
list-style: none;
white-space: nowrap;
}
li {
display: inline;
padding: 0.5rem;
}
With Strict Mode, you immediately see that there is a problem. Strict Mode runs an extra setup+cleanup cycle for every callback ref. This callback ref has no cleanup logic, so it adds refs but doesn't remove them. This is a hint that you're missing a cleanup function.
Strict Mode lets you eagerly find mistakes in callback refs. When you fix your callback by adding a cleanup function in Strict Mode, you also fix many possible future production bugs like the "Scroll to" bug from before:
```js src/index.js import { createRoot } from 'react-dom/client'; import {StrictMode} from 'react'; import './styles.css';
import App from './App';
const root = createRoot(document.getElementById("root")); // ✅ Using StrictMode. root.render( <StrictMode> <App /> </StrictMode> );
```js src/App.js active
import { useRef, useState } from "react";
export default function CatFriends() {
const itemsRef = useRef([]);
const [catList, setCatList] = useState(setupCatList);
const [cat, setCat] = useState('neo');
function scrollToCat(index) {
const list = itemsRef.current;
const {node} = list[index];
node.scrollIntoView({
behavior: "smooth",
block: "nearest",
inline: "center",
});
}
const cats = catList.filter(c => c.type === cat)
return (
<>
<nav>
<button onClick={() => setCat('neo')}>Neo</button>
<button onClick={() => setCat('millie')}>Millie</button>
</nav>
<hr />
<nav>
<span>Scroll to:</span>{cats.map((cat, index) => (
<button key={cat.src} onClick={() => scrollToCat(index)}>
{index}
</button>
))}
</nav>
<div>
<ul>
{cats.map((cat) => (
<li
key={cat.src}
ref={(node) => {
const list = itemsRef.current;
const item = {cat: cat, node};
list.push(item);
console.log(`✅ Adding cat to the map. Total cats: ${list.length}`);
if (list.length > 10) {
console.log('❌ Too many cats in the list!');
}
return () => {
list.splice(list.indexOf(item), 1);
console.log(`❌ Removing cat from the map. Total cats: ${itemsRef.current.length}`);
}
}}
>
<img src={cat.src} />
</li>
))}
</ul>
</div>
</>
);
}
function setupCatList() {
const catList = [];
for (let i = 0; i < 10; i++) {
catList.push({type: 'neo', src: "https://placecats.com/neo/320/240?" + i});
}
for (let i = 0; i < 10; i++) {
catList.push({type: 'millie', src: "https://placecats.com/millie/320/240?" + i});
}
return catList;
}
div {
width: 100%;
overflow: hidden;
}
nav {
text-align: center;
}
button {
margin: .25rem;
}
ul,
li {
list-style: none;
white-space: nowrap;
}
li {
display: inline;
padding: 0.5rem;
}
Now on inital mount in StrictMode, the ref callbacks are all setup, cleaned up, and setup again:
...
✅ Adding animal to the map. Total animals: 10
...
❌ Removing animal from the map. Total animals: 0
...
✅ Adding animal to the map. Total animals: 10
This is expected. Strict Mode confirms that the ref callbacks are cleaned up correctly, so the size never grows above the expected amount. After the fix, there are no memory leaks, and all the features work as expected.
Without Strict Mode, it was easy to miss the bug until you clicked around to app to notice broken features. Strict Mode made the bugs appear right away, before you push them to production.
Fixing deprecation warnings enabled by Strict Mode
React warns if some component anywhere inside a <StrictMode> tree uses one of these deprecated APIs:
UNSAFE_class lifecycle methods likeUNSAFE_componentWillMount. See alternatives.
These APIs are primarily used in older class components so they rarely appear in modern apps.
