'Lifecycle of Reactive Effects'·续3
However, for some reason, the canMove state variable inside handleMove appears to be "stale": it's always true, even after you tick off the checkbox. How is this possible? Find the mistake in the code and fix it.
If you see a linter rule being suppressed, remove the suppression! That's where the mistakes usually are.
```js {expectedErrors: {'react-compiler': [16]}} import { useState, useEffect } from 'react';
export default function App() { const [position, setPosition] = useState({ x: 0, y: 0 }); const [canMove, setCanMove] = useState(true);
function handleMove(e) { if (canMove) { setPosition({ x: e.clientX, y: e.clientY }); } }
useEffect(() => { window.addEventListener('pointermove', handleMove); return () => window.removeEventListener('pointermove', handleMove); // eslint-disable-next-line react-hooks/exhaustive-deps }, []);
return ( <>
```css
body {
height: 200px;
}
The problem with the original code was suppressing the dependency linter. If you remove the suppression, you'll see that this Effect depends on the handleMove function. This makes sense: handleMove is declared inside the component body, which makes it a reactive value. Every reactive value must be specified as a dependency, or it can potentially get stale over time!
The author of the original code has "lied" to React by saying that the Effect does not depend ([]) on any reactive values. This is why React did not re-synchronize the Effect after canMove has changed (and handleMove with it). Because React did not re-synchronize the Effect, the handleMove attached as a listener is the handleMove function created during the initial render. During the initial render, canMove was true, which is why handleMove from the initial render will forever see that value.
If you never suppress the linter, you will never see problems with stale values. There are a few different ways to solve this bug, but you should always start by removing the linter suppression. Then change the code to fix the lint error.
You can change the Effect dependencies to [handleMove], but since it's going to be a newly defined function for every render, you might as well remove dependencies array altogether. Then the Effect will re-synchronize after every re-render:
import { useState, useEffect } from 'react';
export default function App() {
const [position, setPosition] = useState({ x: 0, y: 0 });
const [canMove, setCanMove] = useState(true);
function handleMove(e) {
if (canMove) {
setPosition({ x: e.clientX, y: e.clientY });
}
}
useEffect(() => {
window.addEventListener('pointermove', handleMove);
return () => window.removeEventListener('pointermove', handleMove);
});
return (
<>
<label>
<input type="checkbox"
checked={canMove}
onChange={e => setCanMove(e.target.checked)}
/>
The dot is allowed to move
</label>
<hr />
<div style={{
position: 'absolute',
backgroundColor: 'pink',
borderRadius: '50%',
opacity: 0.6,
transform: `translate(${position.x}px, ${position.y}px)`,
pointerEvents: 'none',
left: -20,
top: -20,
width: 40,
height: 40,
}} />
</>
);
}
body {
height: 200px;
}
This solution works, but it's not ideal. If you put console.log('Resubscribing') inside the Effect, you'll notice that it resubscribes after every re-render. Resubscribing is fast, but it would still be nice to avoid doing it so often.
A better fix would be to move the handleMove function inside the Effect. Then handleMove won't be a reactive value, and so your Effect won't depend on a function. Instead, it will need to depend on canMove which your code now reads from inside the Effect. This matches the behavior you wanted, since your Effect will now stay synchronized with the value of canMove:
import { useState, useEffect } from 'react';
export default function App() {
const [position, setPosition] = useState({ x: 0, y: 0 });
const [canMove, setCanMove] = useState(true);
useEffect(() => {
function handleMove(e) {
if (canMove) {
setPosition({ x: e.clientX, y: e.clientY });
}
}
window.addEventListener('pointermove', handleMove);
return () => window.removeEventListener('pointermove', handleMove);
}, [canMove]);
return (
<>
<label>
<input type="checkbox"
checked={canMove}
onChange={e => setCanMove(e.target.checked)}
/>
The dot is allowed to move
</label>
<hr />
<div style={{
position: 'absolute',
backgroundColor: 'pink',
borderRadius: '50%',
opacity: 0.6,
transform: `translate(${position.x}px, ${position.y}px)`,
pointerEvents: 'none',
left: -20,
top: -20,
width: 40,
height: 40,
}} />
</>
);
}
body {
height: 200px;
}
Try adding console.log('Resubscribing') inside the Effect body and notice that now it only resubscribes when you toggle the checkbox (canMove changes) or edit the code. This makes it better than the previous approach that always resubscribed.
You'll learn a more general approach to this type of problem in Separating Events from Effects.
Fix a connection switch
In this example, the chat service in chat.js exposes two different APIs: createEncryptedConnection and createUnencryptedConnection. The root App component lets the user choose whether to use encryption or not, and then passes down the corresponding API method to the child ChatRoom component as the createConnection prop.
Notice that initially, the console logs say the connection is not encrypted. Try toggling the checkbox on: nothing will happen. However, if you change the selected room after that, then the chat will reconnect and enable encryption (as you'll see from the console messages). This is a bug. Fix the bug so that toggling the checkbox also causes the chat to reconnect.
Suppressing the linter is always suspicious. Could this be a bug?
```js src/App.js import { useState } from 'react'; import ChatRoom from './ChatRoom.js'; import { createEncryptedConnection, createUnencryptedConnection, } from './chat.js';
export default function App() { const [roomId, setRoomId] = useState('general'); const [isEncrypted, setIsEncrypted] = useState(false); return ( <>
```js {expectedErrors: {'react-compiler': [8]}} src/ChatRoom.js active
import { useState, useEffect } from 'react';
export default function ChatRoom({ roomId, createConnection }) {
useEffect(() => {
const connection = createConnection(roomId);
connection.connect();
return () => connection.disconnect();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [roomId]);
return <h1>Welcome to the {roomId} room!</h1>;
}
```js src/chat.js export function createEncryptedConnection(roomId) { // A real implementation would actually connect to the server return { connect() { console.log('✅ 🔐 Connecting to "' + roomId + '... (encrypted)'); }, disconnect() { console.log('❌ 🔐 Disconnected from "' + roomId + '" room (encrypted)'); } }; }
export function createUnencryptedConnection(roomId) { // A real implementation would actually connect to the server return { connect() { console.log('✅ Connecting to "' + roomId + '... (unencrypted)'); }, disconnect() { console.log('❌ Disconnected from "' + roomId + '" room (unencrypted)'); } }; }
```css
label { display: block; margin-bottom: 10px; }
If you remove the linter suppression, you will see a lint error. The problem is that createConnection is a prop, so it's a reactive value. It can change over time! (And indeed, it should--when the user ticks the checkbox, the parent component passes a different value of the createConnection prop.) This is why it should be a dependency. Include it in the list to fix the bug:
```js src/App.js import { useState } from 'react'; import ChatRoom from './ChatRoom.js'; import { createEncryptedConnection, createUnencryptedConnection, } from './chat.js';
export default function App() { const [roomId, setRoomId] = useState('general'); const [isEncrypted, setIsEncrypted] = useState(false); return ( <>
```js src/ChatRoom.js active
import { useState, useEffect } from 'react';
export default function ChatRoom({ roomId, createConnection }) {
useEffect(() => {
const connection = createConnection(roomId);
connection.connect();
return () => connection.disconnect();
}, [roomId, createConnection]);
return <h1>Welcome to the {roomId} room!</h1>;
}
```js src/chat.js export function createEncryptedConnection(roomId) { // A real implementation would actually connect to the server return { connect() { console.log('✅ 🔐 Connecting to "' + roomId + '... (encrypted)'); }, disconnect() { console.log('❌ 🔐 Disconnected from "' + roomId + '" room (encrypted)'); } }; }
export function createUnencryptedConnection(roomId) { // A real implementation would actually connect to the server return { connect() { console.log('✅ Connecting to "' + roomId + '... (unencrypted)'); }, disconnect() { console.log('❌ Disconnected from "' + roomId + '" room (unencrypted)'); } }; }
```css
label { display: block; margin-bottom: 10px; }
It is correct that createConnection is a dependency. However, this code is a bit fragile because someone could edit the App component to pass an inline function as the value of this prop. In that case, its value would be different every time the App component re-renders, so the Effect might re-synchronize too often. To avoid this, you can pass isEncrypted down instead:
```js src/App.js import { useState } from 'react'; import ChatRoom from './ChatRoom.js';
export default function App() { const [roomId, setRoomId] = useState('general'); const [isEncrypted, setIsEncrypted] = useState(false); return ( <>
```js src/ChatRoom.js active
import { useState, useEffect } from 'react';
import {
createEncryptedConnection,
createUnencryptedConnection,
} from './chat.js';
export default function ChatRoom({ roomId, isEncrypted }) {
useEffect(() => {
const createConnection = isEncrypted ?
createEncryptedConnection :
createUnencryptedConnection;
const connection = createConnection(roomId);
connection.connect();
return () => connection.disconnect();
}, [roomId, isEncrypted]);
return <h1>Welcome to the {roomId} room!</h1>;
}
```js src/chat.js export function createEncryptedConnection(roomId) { // A real implementation would actually connect to the server return { connect() { console.log('✅ 🔐 Connecting to "' + roomId + '... (encrypted)'); }, disconnect() { console.log('❌ 🔐 Disconnected from "' + roomId + '" room (encrypted)'); } }; }
export function createUnencryptedConnection(roomId) { // A real implementation would actually connect to the server return { connect() { console.log('✅ Connecting to "' + roomId + '... (unencrypted)'); }, disconnect() { console.log('❌ Disconnected from "' + roomId + '" room (unencrypted)'); } }; } ```
