Skip to content

Commit 2ec5611

Browse files
committed
Document side effects in lazy initialization
1 parent 44b0b5f commit 2ec5611

1 file changed

Lines changed: 36 additions & 0 deletions

File tree

‎src/content/reference/rules/components-and-hooks-must-be-pure.md‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -183,6 +183,42 @@ function ExpenseForm() {
183183
// Continue rendering...
184184
}
185185
```
186+
This is fine because the mutation is local and doesn't affect other components.
187+
188+
Problematic case:
189+
```js
190+
function SubscriptionExample(){
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+
function SubscriptonExample(){
210+
const subscriptionRef = 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.
186222
187223
#### Changing the DOM {/*changing-the-dom*/}
188224

0 commit comments

Comments
 (0)