'Separating Events from Effects'·续1
```js src/notifications.js hidden import Toastify from 'toastify-js'; import 'toastify-js/src/toastify.css';
export function showNotification(message, theme) { Toastify({ text: message, duration: 2000, gravity: 'top', position: 'right', style: { background: theme === 'dark' ? 'black' : 'white', color: theme === 'dark' ? 'white' : 'black', }, }).showToast(); }
```css
label { display: block; margin-top: 10px; }
You can think of Effect Events as being very similar to event handlers. The main difference is that event handlers run in response to user interactions, whereas Effect Events are triggered by you from Effects. Effect Events let you "break the chain" between the reactivity of Effects and code that should not be reactive.
Reading latest props and state with Effect Events
Effect Events let you fix many patterns where you might be tempted to suppress the dependency linter.
For example, say you have an Effect to log the page visits:
function Page() {
useEffect(() => {
logVisit();
}, []);
// ...
}
Later, you add multiple routes to your site. Now your Page component receives a url prop with the current path. You want to pass the url as a part of your logVisit call, but the dependency linter complains:
```js {1,3} function Page({ url }) { useEffect(() => { logVisit(url); }, []); // 🔴 React Hook useEffect has a missing dependency: 'url' // ... }
Think about what you want the code to do. You *want* to log a separate visit for different URLs since each URL represents a different page. In other words, this `logVisit` call *should* be reactive with respect to the `url`. This is why, in this case, it makes sense to follow the dependency linter, and add `url` as a dependency:
```js {4}
function Page({ url }) {
useEffect(() => {
logVisit(url);
}, [url]); // ✅ All dependencies declared
// ...
}
Now let's say you want to include the number of items in the shopping cart together with every page visit:
```js {2-3,6} function Page({ url }) { const { items } = useContext(ShoppingCartContext); const numberOfItems = items.length;
useEffect(() => { logVisit(url, numberOfItems); }, [url]); // 🔴 React Hook useEffect has a missing dependency: 'numberOfItems' // ... }
You used `numberOfItems` inside the Effect, so the linter asks you to add it as a dependency. However, you *don't* want the `logVisit` call to be reactive with respect to `numberOfItems`. If the user puts something into the shopping cart, and the `numberOfItems` changes, this *does not mean* that the user visited the page again. In other words, *visiting the page* is, in some sense, an "event". It happens at a precise moment in time.
Split the code in two parts:
```js {5-7,10}
function Page({ url }) {
const { items } = useContext(ShoppingCartContext);
const numberOfItems = items.length;
const onVisit = useEffectEvent(visitedUrl => {
logVisit(visitedUrl, numberOfItems);
});
useEffect(() => {
onVisit(url);
}, [url]); // ✅ All dependencies declared
// ...
}
Here, onVisit is an Effect Event. The code inside it isn't reactive. This is why you can use numberOfItems (or any other reactive value!) without worrying that it will cause the surrounding code to re-execute on changes.
On the other hand, the Effect itself remains reactive. Code inside the Effect uses the url prop, so the Effect will re-run after every re-render with a different url. This, in turn, will call the onVisit Effect Event.
As a result, you will call logVisit for every change to the url, and always read the latest numberOfItems. However, if numberOfItems changes on its own, this will not cause any of the code to re-run.
[!NOTE]
You might be wondering if you could call
onVisit()with no arguments, and read theurlinside it:```js {2,6} const onVisit = useEffectEvent(() => { logVisit(url, numberOfItems); });
useEffect(() => { onVisit(); }, [url]);
>
> This would work, but it's better to pass this `url` to the Effect Event explicitly. **By passing `url` as an argument to your Effect Event, you are saying that visiting a page with a different `url` constitutes a separate "event" from the user's perspective.** The `visitedUrl` is a *part* of the "event" that happened:
>
```js {1-2,6}
const onVisit = useEffectEvent(visitedUrl => {
logVisit(visitedUrl, numberOfItems);
});
useEffect(() => {
onVisit(url);
}, [url]);
Since your Effect Event explicitly "asks" for the
visitedUrl, now you can't accidentally removeurlfrom the Effect's dependencies. If you remove theurldependency (causing distinct page visits to be counted as one), the linter will warn you about it. You wantonVisitto be reactive with regards to theurl, so instead of reading theurlinside (where it wouldn't be reactive), you pass it from your Effect.This becomes especially important if there is some asynchronous logic inside the Effect:
```js {6,8} const onVisit = useEffectEvent(visitedUrl => { logVisit(visitedUrl, numberOfItems); });
useEffect(() => { setTimeout(() => { onVisit(url); }, 5000); // Delay logging visits }, [url]);
>
> Here, `url` inside `onVisit` corresponds to the *latest* `url` (which could have already changed), but `visitedUrl` corresponds to the `url` that originally caused this Effect (and this `onVisit` call) to run.
>
> [!INFO]
>
> #### Is it okay to suppress the dependency linter instead?
>
> In the existing codebases, you may sometimes see the lint rule suppressed like this:
>
```js {expectedErrors: {'react-compiler': [8]}} {7-9}
function Page({ url }) {
const { items } = useContext(ShoppingCartContext);
const numberOfItems = items.length;
useEffect(() => {
logVisit(url, numberOfItems);
// 🔴 Avoid suppressing the linter like this:
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [url]);
// ...
}
We recommend never suppressing the linter.
The first downside of suppressing the rule is that React will no longer warn you when your Effect needs to "react" to a new reactive dependency you've introduced to your code. In the earlier example, you added
urlto the dependencies because React reminded you to do it. You will no longer get such reminders for any future edits to that Effect if you disable the linter. This leads to bugs.Here is an example of a confusing bug caused by suppressing the linter. In this example, the
handleMovefunction is supposed to read the currentcanMovestate variable value in order to decide whether the dot should follow the cursor. However,canMoveis alwaystrueinsidehandleMove.Can you see why?
```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 this code is in suppressing the dependency linter. If you remove the suppression, you'll see that this Effect should depend on the
handleMovefunction. This makes sense:handleMoveis 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 aftercanMovehas changed (andhandleMovewith it). Because React did not re-synchronize the Effect, thehandleMoveattached as a listener is thehandleMovefunction created during the initial render. During the initial render,canMovewastrue, which is whyhandleMovefrom the initial render will forever see that value.If you never suppress the linter, you will never see problems with stale values.
With
useEffectEvent, there is no need to "lie" to the linter, and the code works as you would expect:
import { useState, useEffect } from 'react';
import { useEffectEvent } from 'react';
export default function App() {
const [position, setPosition] = useState({ x: 0, y: 0 });
const [canMove, setCanMove] = useState(true);
const onMove = useEffectEvent(e => {
if (canMove) {
setPosition({ x: e.clientX, y: e.clientY });
}
});
useEffect(() => {
window.addEventListener('pointermove', onMove);
return () => window.removeEventListener('pointermove', onMove);
}, []);
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 doesn't mean that
useEffectEventis always the correct solution. You should only apply it to the lines of code that you don't want to be reactive. In the above sandbox, you didn't want the Effect's code to be reactive with regards tocanMove. That's why it made sense to extract an Effect Event.Read Removing Effect Dependencies for other correct alternatives to suppressing the linter.
Limitations of Effect Events
Effect Events are very limited in how you can use them:
- Only call them from inside Effects.
- Never pass them to other components or Hooks.
For example, don't declare and pass an Effect Event like this:
```js {4-6,8} function Timer() { const [count, setCount] = useState(0);
const onTick = useEffectEvent(() => { setCount(count + 1); });
useTimer(onTick, 1000); // 🔴 Avoid: Passing Effect Events
return
{count}
}function useTimer(callback, delay) { useEffect(() => { const id = setInterval(() => { callback(); }, delay); return () => { clearInterval(id); }; }, [delay, callback]); // Need to specify "callback" in dependencies }
Instead, always declare Effect Events directly next to the Effects that use them:
```js {10-12,16,21}
function Timer() {
const [count, setCount] = useState(0);
useTimer(() => {
setCount(count + 1);
}, 1000);
return <h1>{count}</h1>
}
function useTimer(callback, delay) {
const onTick = useEffectEvent(() => {
callback();
});
useEffect(() => {
const id = setInterval(() => {
onTick(); // ✅ Good: Only called locally inside an Effect
}, delay);
return () => {
clearInterval(id);
};
}, [delay]); // No need to specify "onTick" (an Effect Event) as a dependency
}
Effect Events are non-reactive "pieces" of your Effect code. They should be next to the Effect using them.
- Event handlers run in response to specific interactions.
- Effects run whenever synchronization is needed.
- Logic inside event handlers is not reactive.
- Logic inside Effects is reactive.
- You can move non-reactive logic from Effects into Effect Events.
- Only call Effect Events from inside Effects.
- Don't pass Effect Events to other components or Hooks.
Fix a variable that doesn't update
This Timer component keeps a count state variable which increases every second. The value by which it's increasing is stored in the increment state variable. You can control the increment variable with the plus and minus buttons.
However, no matter how many times you click the plus button, the counter is still incremented by one every second. What's wrong with this code? Why is increment always equal to 1 inside the Effect's code? Find the mistake and fix it.
To fix this code, it's enough to follow the rules.
```js {expectedErrors: {'react-compiler': [14]}} import { useState, useEffect } from 'react';
export default function Timer() { const [count, setCount] = useState(0); const [increment, setIncrement] = useState(1);
useEffect(() => { const id = setInterval(() => { setCount(c => c + increment); }, 1000); return () => { clearInterval(id); }; // eslint-disable-next-line react-hooks/exhaustive-deps }, []);
return ( <>
Counter: {count}
Every second, increment by: {increment}
</> ); }
```css
button { margin: 10px; }
As usual, when you're looking for bugs in Effects, start by searching for linter suppressions.
If you remove the suppression comment, React will tell you that this Effect's code depends on increment, but you "lied" to React by claiming that this Effect does not depend on any reactive values ([]). Add increment to the dependency array:
import { useState, useEffect } from 'react';
export default function Timer() {
const [count, setCount] = useState(0);
const [increment, setIncrement] = useState(1);
useEffect(() => {
const id = setInterval(() => {
setCount(c => c + increment);
}, 1000);
return () => {
clearInterval(id);
};
}, [increment]);
return (
<>
<h1>
Counter: {count}
<button onClick={() => setCount(0)}>Reset</button>
</h1>
<hr />
<p>
Every second, increment by:
<button disabled={increment === 0} onClick={() => {
setIncrement(i => i - 1);
}}>–</button>
<b>{increment}</b>
<button onClick={() => {
setIncrement(i => i + 1);
}}>+</button>
</p>
</>
);
}
button { margin: 10px; }
Now, when increment changes, React will re-synchronize your Effect, which will restart the interval.
Fix a freezing counter
This Timer component keeps a count state variable which increases every second. The value by which it's increasing is stored in the increment state variable, which you can control it with the plus and minus buttons. For example, try pressing the plus button nine times, and notice that the count now increases each second by ten rather than by one.
There is a small issue with this user interface. You might notice that if you keep pressing the plus or minus buttons faster than once per second, the timer itself seems to pause. It only resumes after a second passes since the last time you've pressed either button. Find why this is happening, and fix the issue so that the timer ticks on every second without interruptions.
It seems like the Effect which sets up the timer "reacts" to the increment value. Does the line that uses the current increment value in order to call setCount really need to be reactive?
import { useState, useEffect } from 'react';
import { useEffectEvent } from 'react';
export default function Timer() {
const [count, setCount] = useState(0);
const [increment, setIncrement] = useState(1);
useEffect(() => {
const id = setInterval(() => {
setCount(c => c + increment);
}, 1000);
return () => {
clearInterval(id);
};
}, [increment]);
return (
<>
<h1>
Counter: {count}
<button onClick={() => setCount(0)}>Reset</button>
</h1>
<hr />
<p>
Every second, increment by:
<button disabled={increment === 0} onClick={() => {
setIncrement(i => i - 1);
}}>–</button>
<b>{increment}</b>
<button onClick={() => {
setIncrement(i => i + 1);
}}>+</button>
</p>
</>
);
}
button { margin: 10px; }
The issue is that the code inside the Effect uses the increment state variable. Since it's a dependency of your Effect, every change to increment causes the Effect to re-synchronize, which causes the interval to clear. If you keep clearing the interval every time before it has a chance to fire, it will appear as if the timer has stalled.
