Skip to content

Commit b762ba6

Browse files
committed
Add advanced useEffect hooks
1 parent bd14a88 commit b762ba6

File tree

1 file changed

+150
-17
lines changed

1 file changed

+150
-17
lines changed

README.md

Lines changed: 150 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -4946,11 +4946,25 @@ class ParentComponent extends React.Component {
49464946
49474947
**[⬆ Back to Top](#table-of-contents)**
49484948
4949-
217. ### How to fetch data with React Hooks?
4949+
217. ### What is useEffect hook? How to fetch data with React Hooks?
49504950
4951-
The effect hook called `useEffect` can be used to fetch data from an API and to set the data in the local state of the component with the useState hook’s update function.
4951+
The `useEffect` hook is a React Hook that lets you perform **side effects** in function components. Side effects are operations that interact with the outside world or system and aren't directly related to rendering UI — such as fetching data, setting up subscriptions, timers, manually manipulating the DOM, etc.
49524952
4953-
Here is an example of fetching a list of react articles from an API using fetch.
4953+
In function components, useEffect replaces the class component lifecycle methods(`componentDidMount`, `componentDidUpdate` and `componentWillUnmount`) with a single, unified API.
4954+
4955+
**Syntax**
4956+
```js
4957+
useEffect(() => {
4958+
// Side effect logic here
4959+
4960+
return () => {
4961+
// Cleanup logic (optional)
4962+
};
4963+
}, [dependencies]);
4964+
```
4965+
This effect hook can be used to fetch data from an API and to set the data in the local state of the component with the useState hook’s update function.
4966+
4967+
Here is an example of fetching a list of ReactJS articles from an API using fetch.
49544968
49554969
```javascript
49564970
import React from "react";
@@ -6862,6 +6876,125 @@ Technically it is possible to write nested function components but it is not sug
68626876
68636877
**[⬆ Back to Top](#table-of-contents)**
68646878
6879+
287. ### How do reactive dependencies in the useEffect dependency array affect its execution behavior?
6880+
The `useEffect` hook accepts an optional dependencies argument that accepts an array of reactive values. The **dependency array** determines **when** the effect runs. i.e, It makes `useEffect` _reactive_ to changes in specified values.
6881+
6882+
#### **How Dependency Array Affects Behavior**
6883+
6884+
1. **Empty Dependency Array:** `**[]**`
6885+
6886+
```css
6887+
useEffect(() => {
6888+
// runs once after the initial render
6889+
}, []);
6890+
```
6891+
6892+
* Effect runs **only once** (like `componentDidMount`).
6893+
* Ignores all state/prop changes.
6894+
6895+
2. **With Specific Dependencies:** `**[count, user]**`
6896+
6897+
```css
6898+
useEffect(() => {
6899+
// runs after initial render
6900+
// AND whenever `count` or `user` changes
6901+
}, [count, user]);
6902+
```
6903+
6904+
* Effect runs on **first render**, and
6905+
* Again **every time** any dependency value changes.
6906+
6907+
3. **No Dependency Array (Omitted)**
6908+
6909+
```css
6910+
useEffect(() => {
6911+
// runs after **every** render
6912+
});
6913+
```
6914+
6915+
* Effect runs after **every render**, regardless of what changed.
6916+
* Can lead to **performance issues** if not used carefully.
6917+
6918+
React uses shallow comparison of the dependencies. If any value has changed (!==), the effect will re-run.
6919+
6920+
**Note:** This hook works well when dependencies are primitives or memoized objects/functions.
6921+
6922+
**[⬆ Back to Top](#table-of-contents)**
6923+
6924+
288. ### When and how often does React invoke the setup and cleanup functions inside a useEffect hook?
6925+
6926+
1. **Setup Function Execution (`useEffect`)**
6927+
6928+
The setup function (or the main function) you pass to `useEffect` runs at specific points:
6929+
6930+
1. **After the component is mounted** (if the dependency array is empty `[]`)
6931+
2. **After every render** (if no dependency array is provided)
6932+
3. **After a dependency value changes** (if the dependency array contains variables)
6933+
6934+
2. **Cleanup Function Execution (Returned function from `useEffect`)**
6935+
6936+
The cleanup function is called **before the effect is re-executed** and when the component **unmounts**.
6937+
6938+
**[⬆ Back to Top](#table-of-contents)**
6939+
6940+
289. ### What happens if you return a Promise from useEffect??
6941+
You should NOT return a Promise from useEffect. React expects the function passed to useEffect to return either nothing (undefined) or a cleanup function (synchronous function). i.e, It does not expect or handle a returned Promise. If you still return a Promise, React will ignore it silently, and it may lead to bugs or warnings in strict mode.
6942+
6943+
**Incorrect:**
6944+
```js
6945+
useEffect(async () => {
6946+
await fetchData(); // ❌ useEffect shouldn't be async
6947+
}, []);
6948+
```
6949+
**Correct:**
6950+
```jsx
6951+
useEffect(() => {
6952+
const fetchData = async () => {
6953+
const res = await fetch('/api');
6954+
const data = await res.json();
6955+
setData(data);
6956+
};
6957+
6958+
fetchData();
6959+
}, []);
6960+
```
6961+
**[⬆ Back to Top](#table-of-contents)**
6962+
6963+
289. ### Can you have multiple useEffect hooks in a single component?
6964+
Yes, multiple useEffect hooks are allowed and recommended when you want to separate concerns.
6965+
6966+
```jsx
6967+
useEffect(() => {
6968+
// Handles API fetch
6969+
}, []);
6970+
6971+
useEffect(() => {
6972+
// Handles event listeners
6973+
}, []);
6974+
```
6975+
Each effect runs independently and helps make code modular and easier to debug.
6976+
6977+
**[⬆ Back to Top](#table-of-contents)**
6978+
6979+
290. ### How to prevent infinite loops with useEffect?
6980+
Infinite loops happen when the effect updates state that’s listed in its own dependency array, which causes the effect to re-run, updating state again and so on.
6981+
6982+
**Infinite loop scenario:**
6983+
```js
6984+
useEffect(() => {
6985+
setCount(count + 1);
6986+
}, [count]); // Triggers again every time count updates
6987+
```
6988+
You need to ensure that setState calls do not depend on values that cause the effect to rerun, or isolate them with a guard.
6989+
```js
6990+
useEffect(() => {
6991+
if (count < 5) {
6992+
setCount(count + 1);
6993+
}
6994+
}, [count]);
6995+
```
6996+
**[⬆ Back to Top](#table-of-contents)**
6997+
68656998
## Old Q&A
68666999
68677000
1. ### Why should we not update the state directly?
@@ -6908,7 +7041,7 @@ Technically it is possible to write nested function components but it is not sug
69087041
69097042
**[⬆ Back to Top](#table-of-contents)**
69107043
6911-
1. ### How to bind methods or event handlers in JSX callbacks?
7044+
3. ### How to bind methods or event handlers in JSX callbacks?
69127045
69137046
There are 3 possible ways to achieve this in class components:
69147047
@@ -6956,7 +7089,7 @@ Technically it is possible to write nested function components but it is not sug
69567089
69577090
**[⬆ Back to Top](#table-of-contents)**
69587091
6959-
2. ### How to pass a parameter to an event handler or callback?
7092+
4. ### How to pass a parameter to an event handler or callback?
69607093
69617094
You can use an _arrow function_ to wrap around an _event handler_ and pass parameters:
69627095
@@ -6981,13 +7114,13 @@ Technically it is possible to write nested function components but it is not sug
69817114
69827115
**[⬆ Back to Top](#table-of-contents)**
69837116
6984-
3. ### What is the use of refs?
7117+
5. ### What is the use of refs?
69857118
69867119
The _ref_ is used to return a reference to the element. They _should be avoided_ in most cases, however, they can be useful when you need a direct access to the DOM element or an instance of a component.
69877120
69887121
**[⬆ Back to Top](#table-of-contents)**
69897122
6990-
4. ### How to create refs?
7123+
6. ### How to create refs?
69917124
69927125
There are two approaches
69937126
@@ -7036,7 +7169,7 @@ Technically it is possible to write nested function components but it is not sug
70367169
70377170
**[⬆ Back to Top](#table-of-contents)**
70387171
7039-
5. ### What are forward refs?
7172+
7. ### What are forward refs?
70407173
70417174
_Ref forwarding_ is a feature that lets some components take a _ref_ they receive, and pass it further down to a child.
70427175
@@ -7054,7 +7187,7 @@ Technically it is possible to write nested function components but it is not sug
70547187
70557188
**[⬆ Back to Top](#table-of-contents)**
70567189
7057-
6. ### Which is preferred option with in callback refs and findDOMNode()?
7190+
8. ### Which is preferred option with in callback refs and findDOMNode()?
70587191
70597192
It is preferred to use _callback refs_ over `findDOMNode()` API. Because `findDOMNode()` prevents certain improvements in React in the future.
70607193
@@ -7092,7 +7225,7 @@ Technically it is possible to write nested function components but it is not sug
70927225
70937226
**[⬆ Back to Top](#table-of-contents)**
70947227
7095-
7. ### Why are String Refs legacy?
7228+
9. ### Why are String Refs legacy?
70967229
70977230
If you worked with React before, you might be familiar with an older API where the `ref` attribute is a string, like `ref={'textInput'}`, and the DOM node is accessed as `this.refs.textInput`. We advise against it because _string refs have below issues_, and are considered legacy. String refs were **removed in React v16**.
70987231
@@ -7121,7 +7254,7 @@ Technically it is possible to write nested function components but it is not sug
71217254
71227255
**[⬆ Back to Top](#table-of-contents)**
71237256
7124-
8. ### What are the different phases of component lifecycle?
7257+
10. ### What are the different phases of component lifecycle?
71257258
71267259
The component lifecycle has three distinct lifecycle phases:
71277260
@@ -7149,7 +7282,7 @@ Technically it is possible to write nested function components but it is not sug
71497282

71507283
**[⬆ Back to Top](#table-of-contents)**
71517284

7152-
9. ### What are the lifecycle methods of React?
7285+
11. ### What are the lifecycle methods of React?
71537286

71547287
Before React 16.3
71557288

@@ -7172,7 +7305,7 @@ Technically it is possible to write nested function components but it is not sug
71727305

71737306
**[⬆ Back to Top](#table-of-contents)**
71747307

7175-
10. ### How to create props proxy for HOC component?
7308+
12. ### How to create props proxy for HOC component?
71767309

71777310
You can add/edit props passed to the component using _props proxy_ pattern like this:
71787311

@@ -7195,7 +7328,7 @@ Technically it is possible to write nested function components but it is not sug
71957328
71967329
**[⬆ Back to Top](#table-of-contents)**
71977330
7198-
11. ### What is context?
7331+
13. ### What is context?
71997332
72007333
_Context_ provides a way to pass data through the component tree without having to pass props down manually at every level.
72017334
@@ -7207,7 +7340,7 @@ Technically it is possible to write nested function components but it is not sug
72077340
72087341
**[⬆ Back to Top](#table-of-contents)**
72097342
7210-
12. ### What is the purpose of using super constructor with props argument?
7343+
14. ### What is the purpose of using super constructor with props argument?
72117344
72127345
A child class constructor cannot make use of `this` reference until the `super()` method has been called. The same applies to ES6 sub-classes as well. The main reason for passing props parameter to `super()` call is to access `this.props` in your child constructors.
72137346
@@ -7247,7 +7380,7 @@ Technically it is possible to write nested function components but it is not sug
72477380
72487381
**[⬆ Back to Top](#table-of-contents)**
72497382
7250-
13. ### How to set state with a dynamic key name?
7383+
15. ### How to set state with a dynamic key name?
72517384
72527385
If you are using ES6 or the Babel transpiler to transform your JSX code then you can accomplish this with _computed property names_.
72537386
@@ -7259,7 +7392,7 @@ Technically it is possible to write nested function components but it is not sug
72597392
72607393
**[⬆ Back to Top](#table-of-contents)**
72617394
7262-
14. ### What would be the common mistake of function being called every time the component renders?
7395+
16. ### What would be the common mistake of function being called every time the component renders?
72637396
72647397
You need to make sure that function is not being called while passing the function as a parameter.
72657398

0 commit comments

Comments
 (0)