Skip to content

Commit 365f59d

Browse files
Surjit Kumar SahooSurjit Kumar Sahoo
authored andcommitted
add how to think about use-effect?
1 parent ebc5d78 commit 365f59d

2 files changed

Lines changed: 67 additions & 1 deletion

File tree

docs/4.performance/2.what-are-hooks.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ sidebar_position: 2
33
slug: what-are-hooks
44
---
55

6-
# What Are Hooks?
6+
# What Are Hooks? 🪝
77

88
:::info Hooks are all about memoization
99
It is an optimization technique.
Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
---
2+
sidebar_position: 4
3+
slug: how-to-think-about-use-effect
4+
title: How to think about useEffect
5+
---
6+
7+
# How to think about `useEffect`?
8+
9+
## `useDefect` or `useFootGun` 🦶🏼🔫
10+
11+
Yes, I'm not kidding, useEffect can produce hard-to-understand, un-maintainable, unpredictable code. Chained useEffects can also produce cascading chain reactions of unpredictability if not used properly. **In most cases, you do not need useEffect, it can be handled with event driven approach.**
12+
13+
But that doesn't mean there's no use of useEffect. It's primary use is to handle subscriptions. When the component mounts you want to subscribe to some-stuff, and then when the component un-mounts, you cleanup the subscriptions.
14+
15+
:::tip
16+
Think of useEffect as `useSynchronize`
17+
:::
18+
Imagine you're watching TV, if you change channels, the content of that TV channel doesn't stop coming, You just don't care about that content anymore, that's all. useEffect helps you subscribe to the desired channel, consume content and when you're done, you can unsubscribe.
19+
20+
### React 18 made it clear
21+
22+
In React 18, the following code will run twice, not once!
23+
24+
```jsx showLineNumbers title="BAD 💩🧨💣"
25+
function App() {
26+
// ...
27+
28+
useEffect(() => {
29+
authenticate();
30+
}, []);
31+
32+
// ...
33+
}
34+
```
35+
36+
- It's react's way of telling you, you're not using `useEffect` as intended!
37+
- Your components must be robust to component updates and mounts.
38+
39+
```jsx showLineNumbers title="Hack | Workaround"
40+
let initialized = false;
41+
42+
function App() {
43+
//...
44+
45+
useEffect(() => {
46+
if (!initialized) {
47+
initialized = true;
48+
authenticate();
49+
}
50+
}, []);
51+
52+
// ...
53+
}
54+
```
55+
56+
```jsx showLineNumbers title="Or just remove the useEffect all-together ✅"
57+
// If you're using Next.JS check you're running in browser
58+
if (typeof window !== 'undefined') {
59+
// ✅ Only runs once per app load
60+
authenticate();
61+
}
62+
63+
function App() {
64+
//...
65+
}
66+
```

0 commit comments

Comments
 (0)