Skip to content

Commit d434238

Browse files
authored
Merge pull request #4332 from CodeHarborHub/dev-3
Dev 3: new content in Js Data Type || new update in blog
2 parents 4a0de7b + 8d7837c commit d434238

File tree

66 files changed

+1721
-1513
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

66 files changed

+1721
-1513
lines changed

blog/Beginner’s Guide to the Top 5 React Hooks.md

Lines changed: 44 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,16 @@
11
---
2-
title: 'A Beginner’s Guide to the Top 5 React Hooks'
2+
title: "A Beginner’s Guide to the Top 5 React Hooks"
33
sidebar_label: React hooks
44
authors: [dharshibalasubramaniyam]
55
tags: [react.js, react-hooks]
66
date: 2024-06-19
77
hide_table_of_contents: true
88
---
99

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+
1014
## Why React Hooks?
1115

1216
### Evolution of React:
@@ -32,7 +36,7 @@ hide_table_of_contents: true
3236
### Importing useState hook from react:
3337

3438
```js
35-
import { useState } from 'react';
39+
import { useState } from "react";
3640
```
3741

3842
### Declaring a state variable named count with an initial value of 0,
@@ -57,6 +61,7 @@ const Counter = () => {
5761
);
5862
};
5963
```
64+
6065
- 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.
6166

6267
- Note: We cannot update a state variable like, count = count +1
@@ -67,29 +72,26 @@ const Counter = () => {
6772

6873
```js
6974
const Counter = () => {
70-
const [person, setPerson] = useState({id: '1', name: 'John', age: 25});
75+
const [person, setPerson] = useState({ id: "1", name: "John", age: 25 });
7176

7277
const updateName = (newName) => {
73-
setPerson(prevState => {
78+
setPerson((prevState) => {
7479
return { ...prevState, name: newName };
7580
});
7681
};
7782

7883
const updateAge = (newAge) => {
79-
setPerson(prevState => {
84+
setPerson((prevState) => {
8085
return { ...prevState, age: newAge };
8186
});
8287
};
8388

84-
return (
85-
<div>
86-
{/* form to update name and age */}
87-
</div>
88-
);
89+
return <div>{/* form to update name and age */}</div>;
8990
};
9091
```
9192

9293
## 2. ‘useEffect’ hook
94+
9395
- 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.
9496

9597
### componentDidMount
@@ -101,7 +103,7 @@ const Counter = () => {
101103
```js
102104
useEffect(() => {
103105
// Perform initialization or side effects
104-
console.log("The component is rendered initially.")
106+
console.log("The component is rendered initially.");
105107
}, []);
106108
```
107109

@@ -114,7 +116,7 @@ useEffect(() => {
114116
```js
115117
useEffect(() => {
116118
// Effect runs after every render
117-
console.log("The component is rendered.")
119+
console.log("The component is rendered.");
118120
});
119121
```
120122

@@ -123,7 +125,7 @@ useEffect(() => {
123125
```js
124126
useEffect(() => {
125127
// Perform side effects after state or props update
126-
console.log("dependency1 or dependency2 have updated.")
128+
console.log("dependency1 or dependency2 have updated.");
127129
}, [dependency1, dependency2]);
128130
```
129131

@@ -136,10 +138,10 @@ useEffect(() => {
136138
```js
137139
useEffect(() => {
138140
// Perform side effects
139-
console.log("dependency is updated.")
141+
console.log("dependency is updated.");
140142
return () => {
141143
// Cleanup tasks
142-
console.log("The component is unmounted.")
144+
console.log("The component is unmounted.");
143145
};
144146
}, [dependency]);
145147
```
@@ -154,7 +156,7 @@ useEffect(() => {
154156

155157
```js
156158
// themeContext.js
157-
import React, { createContext } from 'react';
159+
import React, { createContext } from "react";
158160

159161
export const ThemeContext = createContext(null);
160162
```
@@ -165,11 +167,11 @@ export const ThemeContext = createContext(null);
165167

166168
```js
167169
function App() {
168-
const theme = 'dark';
170+
const theme = "dark";
169171

170172
return (
171173
<ThemeContext.Provider value={theme}>
172-
<MyComponent/>
174+
<MyComponent />
173175
</ThemeContext.Provider>
174176
);
175177
}
@@ -180,20 +182,21 @@ function App() {
180182
- Now, any component within the provider can access the context using the useContext hook.
181183

182184
```js
183-
import React, { useContext } from 'react';
184-
import ThemeContext from './ThemeContext';
185+
import React, { useContext } from "react";
186+
import ThemeContext from "./ThemeContext";
185187

186188
function MyComponent() {
187189
const theme = useContext(ThemeContext);
188190

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+
);
197200
}
198201
```
199202

@@ -214,25 +217,21 @@ const Counter = () => {
214217
// Step 1: Define initial state
215218
const initialState = { count: 0 };
216219

217-
return (
218-
<div>
219-
content
220-
</div>
221-
);
220+
return <div>content</div>;
222221
};
223222
```
224223

225224
### Reducer Function
226225

227226
- 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.
228-
227+
229228
```js
230229
// Step 2: Define reducer function
231230
const reducer = (state, action) => {
232231
switch (action.type) {
233-
case 'increment':
232+
case "increment":
234233
return { count: state.count + 1 };
235-
case 'decrement':
234+
case "decrement":
236235
return { count: state.count - 1 };
237236
default:
238237
throw new Error();
@@ -247,15 +246,15 @@ const reducer = (state, action) => {
247246
```js
248247
const Counter = () => {
249248
const initialState = { count: 0 };
250-
249+
251250
// Step 3: Use useReducer hook
252251
const [state, dispatch] = useReducer(reducer, initialState);
253252

254253
return (
255254
<div>
256255
Count: {state.count}
257-
<button onClick={() => dispatch({ type: 'increment' })}>+</button>
258-
<button onClick={() => dispatch({ type: 'decrement' })}>-</button>
256+
<button onClick={() => dispatch({ type: "increment" })}>+</button>
257+
<button onClick={() => dispatch({ type: "decrement" })}>-</button>
259258
</div>
260259
);
261260
};
@@ -272,7 +271,7 @@ const Counter = () => {
272271
Example 1
273272

274273
```js
275-
import React, { useRef } from 'react';
274+
import React, { useRef } from "react";
276275

277276
function MyComponent() {
278277
// Create a ref to store a DOM element
@@ -301,7 +300,7 @@ In this example, myInputRef is created using useRef, and it's attached to the in
301300
Example 2
302301

303302
```js
304-
import React, { useState, useRef } from 'react';
303+
import React, { useState, useRef } from "react";
305304

306305
function Counter() {
307306
// State for storing the count
@@ -316,10 +315,10 @@ function Counter() {
316315
if (intervalIdRef.current !== null) {
317316
return; // If already running, do nothing
318317
}
319-
318+
320319
// Start the counter
321320
intervalIdRef.current = setInterval(() => {
322-
setCount(prevCount => prevCount + 1);
321+
setCount((prevCount) => prevCount + 1);
323322
}, 1000);
324323
};
325324

@@ -329,7 +328,7 @@ function Counter() {
329328
if (intervalIdRef.current === null) {
330329
return; // If not running, do nothing
331330
}
332-
331+
333332
// Stop the counter
334333
clearInterval(intervalIdRef.current);
335334
intervalIdRef.current = null;
@@ -346,6 +345,7 @@ function Counter() {
346345

347346
export default Counter;
348347
```
348+
349349
- We have a state variable count that stores the current count.
350350
- 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.
351351
- 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

Comments
 (0)