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: blog/Beginner’s Guide to the Top 5 React Hooks.md
+44-44Lines changed: 44 additions & 44 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -1,12 +1,16 @@
1
1
---
2
-
title: 'A Beginner’s Guide to the Top 5 React Hooks'
2
+
title: "A Beginner’s Guide to the Top 5 React Hooks"
3
3
sidebar_label: React hooks
4
4
authors: [dharshibalasubramaniyam]
5
5
tags: [react.js, react-hooks]
6
6
date: 2024-06-19
7
7
hide_table_of_contents: true
8
8
---
9
9
10
+
In this beginner’s guide, we’ll explore the top 5 React hooks that every React developer should know. React hooks are a powerful feature introduced in React 16.8 that allow you to use state and other React features in functional components. They provide a more elegant and composable way to manage component logic compared to class components. Let’s dive into the top 5 React hooks you should be familiar with.
11
+
12
+
<!-- truncate -->
13
+
10
14
## Why React Hooks?
11
15
12
16
### Evolution of React:
@@ -32,7 +36,7 @@ hide_table_of_contents: true
32
36
### Importing useState hook from react:
33
37
34
38
```js
35
-
import { useState } from'react';
39
+
import { useState } from"react";
36
40
```
37
41
38
42
### Declaring a state variable named count with an initial value of 0,
@@ -57,6 +61,7 @@ const Counter = () => {
57
61
);
58
62
};
59
63
```
64
+
60
65
- In above example, when the button is clicked, the onClick event handler calls the setCount function with the updated value of count (count + 1), causing the component to re-render with the new state value.
61
66
62
67
- Note: We cannot update a state variable like, count = count +1
return<div>{/* form to update name and age */}</div>;
89
90
};
90
91
```
91
92
92
93
## 2. ‘useEffect’ hook
94
+
93
95
- The useEffect hook in React enables functional components to perform side effects, such as data fetching, DOM manipulation, or subscriptions. It replaces lifecycle methods like componentDidMount, componentDidUpdate, and componentWillUnmount in class components.
94
96
95
97
### componentDidMount
@@ -101,7 +103,7 @@ const Counter = () => {
101
103
```js
102
104
useEffect(() => {
103
105
// Perform initialization or side effects
104
-
console.log("The component is rendered initially.")
106
+
console.log("The component is rendered initially.");
105
107
}, []);
106
108
```
107
109
@@ -114,7 +116,7 @@ useEffect(() => {
114
116
```js
115
117
useEffect(() => {
116
118
// Effect runs after every render
117
-
console.log("The component is rendered.")
119
+
console.log("The component is rendered.");
118
120
});
119
121
```
120
122
@@ -123,7 +125,7 @@ useEffect(() => {
123
125
```js
124
126
useEffect(() => {
125
127
// Perform side effects after state or props update
126
-
console.log("dependency1 or dependency2 have updated.")
128
+
console.log("dependency1 or dependency2 have updated.");
- Now, any component within the provider can access the context using the useContext hook.
181
183
182
184
```js
183
-
importReact, { useContext } from'react';
184
-
importThemeContextfrom'./ThemeContext';
185
+
importReact, { useContext } from"react";
186
+
importThemeContextfrom"./ThemeContext";
185
187
186
188
functionMyComponent() {
187
189
consttheme=useContext(ThemeContext);
188
190
189
-
return<div
190
-
style={{
191
-
background: theme ==='dark'?
192
-
'#222':'#fff' }
193
-
}
194
-
>
195
-
Content
196
-
</div>;
191
+
return (
192
+
<div
193
+
style={{
194
+
background: theme ==="dark"?"#222":"#fff",
195
+
}}
196
+
>
197
+
Content
198
+
</div>
199
+
);
197
200
}
198
201
```
199
202
@@ -214,25 +217,21 @@ const Counter = () => {
214
217
// Step 1: Define initial state
215
218
constinitialState= { count:0 };
216
219
217
-
return (
218
-
<div>
219
-
content
220
-
</div>
221
-
);
220
+
return<div>content</div>;
222
221
};
223
222
```
224
223
225
224
### Reducer Function
226
225
227
226
- You define a reducer function. This function takes two arguments: the current state and an action, and returns the new state based on the action. The reducer function is responsible for updating the state.
@@ -301,7 +300,7 @@ In this example, myInputRef is created using useRef, and it's attached to the in
301
300
Example 2
302
301
303
302
```js
304
-
importReact, { useState, useRef } from'react';
303
+
importReact, { useState, useRef } from"react";
305
304
306
305
functionCounter() {
307
306
// State for storing the count
@@ -316,10 +315,10 @@ function Counter() {
316
315
if (intervalIdRef.current!==null) {
317
316
return; // If already running, do nothing
318
317
}
319
-
318
+
320
319
// Start the counter
321
320
intervalIdRef.current=setInterval(() => {
322
-
setCount(prevCount=> prevCount +1);
321
+
setCount((prevCount)=> prevCount +1);
323
322
}, 1000);
324
323
};
325
324
@@ -329,7 +328,7 @@ function Counter() {
329
328
if (intervalIdRef.current===null) {
330
329
return; // If not running, do nothing
331
330
}
332
-
331
+
333
332
// Stop the counter
334
333
clearInterval(intervalIdRef.current);
335
334
intervalIdRef.current=null;
@@ -346,6 +345,7 @@ function Counter() {
346
345
347
346
exportdefaultCounter;
348
347
```
348
+
349
349
- We have a state variable count that stores the current count.
350
350
- We create a ref named intervalIdRef using useRef(null). This ref will be used to store the ID returned by setInterval so that we can later clear the interval.
351
351
- startCounter function starts a timer using setInterval and increments the count every second. It first checks if the counter is already running to avoid starting multiple timers simultaneously.
0 commit comments