You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: src/content/reference/rules/components-and-hooks-must-be-pure.md
+36Lines changed: 36 additions & 0 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -183,6 +183,42 @@ function ExpenseForm() {
183
183
// Continue rendering...
184
184
}
185
185
```
186
+
This is fine because the mutation is local and doesn't affect other components.
187
+
188
+
Problematic case:
189
+
```js
190
+
functionSubscriptionExample(){
191
+
let subscriptionRef =useRef(null);
192
+
// 🔴 Don't do this during render
193
+
if(subscriptionRef.current==null){
194
+
subscriptionRef.current=store.subscribe(() => {
195
+
console.log("Store Changed")
196
+
});
197
+
}
198
+
useEffect(() =>{
199
+
return () =>{
200
+
subscriptionRef.current?.unsubscribe();
201
+
}
202
+
},[]);
203
+
}
204
+
```
205
+
This is a problematic use of lazy initialization because it perfroms an external side effect during render. If React abandons the render, the subscription may remain active without its cleanup .
206
+
207
+
Correct approach:
208
+
```js
209
+
functionSubscriptonExample(){
210
+
constsubscriptionRef=useRef(null);
211
+
useEffect(() =>{
212
+
subscriptionRef.current=store.subscribe(() =>{
213
+
// ..
214
+
})
215
+
return () =>{
216
+
subscriptionRef.current?.unsubscribe();
217
+
}
218
+
},[]);
219
+
}
220
+
```
221
+
For resources that require setup and cleanup, initialize them inside an Effect.
0 commit comments