Skip to content

Commit 6ca8c6c

Browse files
fixed_issue
1 parent c5ae48e commit 6ca8c6c

File tree

8 files changed

+289
-0
lines changed

8 files changed

+289
-0
lines changed

docs/react/hooks/_category_.json

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
{
2+
"label": "Hooks",
3+
"position": 5,
4+
"link": {
5+
"type": "generated-index",
6+
"description": "5 minutes to learn the most important RoadMap for React Mastery."
7+
}
8+
}

docs/react/hooks/useCallback.md

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
---
2+
id: useCallback hook
3+
title: useCallback Hook Concept
4+
sidebar_label: useCallback Hook
5+
sidebar_position: 5
6+
tags: [react, create-react-app, useCallback, hooks, react-scripts, react-dom, react-app]
7+
---
8+
### useCallback
9+
10+
**Explanation:**
11+
`useCallback` is used to memoize functions to prevent unnecessary renders in child components. It is particularly useful when passing callbacks to optimized child components that rely on reference equality to prevent unnecessary renders.
12+
13+
When you call `useCallback`, you pass it a function and a dependency array. It returns a memoized version of the callback function that only changes if one of the dependencies has changed.
14+
15+
**Example:**
16+
```jsx
17+
import React, { useState, useCallback } from 'react';
18+
19+
function MemoizedCounter() {
20+
const [count, setCount] = useState(0);
21+
22+
// Memoize 'increment' function to prevent unnecessary renders
23+
const increment = useCallback(() => {
24+
setCount(count + 1);
25+
}, [count]);
26+
27+
return (
28+
<div>
29+
<p>Count: {count}</p>
30+
{/* Button uses memoized 'increment' function */}
31+
<button onClick={increment}>Increment</button>
32+
</div>
33+
);
34+
}
35+
```
36+
37+
In this example, `useCallback` memoizes the `increment` function to ensure that it only changes when `count` changes. This optimization prevents unnecessary re-renders of `MemoizedCounter` when passed as a prop to child components.

docs/react/hooks/useContext.md

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
---
2+
id: useContext hook
3+
title: useContext Hook Concept
4+
sidebar_label: useContext Hook
5+
sidebar_position: 3
6+
tags: [react, create-react-app, useContext, hooks, react-scripts, react-dom, react-app]
7+
---
8+
9+
### useContext
10+
11+
**Explanation:**
12+
`useContext` provides a way to pass data through the component tree without having to pass props down manually at every level. It allows you to access values from the nearest `Context.Provider` in the tree.
13+
14+
When you call `useContext`, you pass it the context object that was created with `React.createContext()`. It returns the current context value for that context, determined by the nearest provider above the calling component in the tree.
15+
16+
**Example:**
17+
```jsx
18+
import React, { useContext } from 'react';
19+
20+
// Create a context object with a default value ('light')
21+
const ThemeContext = React.createContext('light');
22+
23+
function ThemeComponent() {
24+
// Use 'useContext' to access the current theme value ('light')
25+
const theme = useContext(ThemeContext);
26+
27+
return <p>Current theme: {theme}</p>;
28+
}
29+
```
30+
31+
In this example, `ThemeComponent` uses `useContext` to consume the current theme value (`'light'`) provided by the nearest `ThemeContext.Provider` higher up in the component tree.

docs/react/hooks/useEffect-hook.md

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
---
2+
id: useEffect hook
3+
title: useEffect Hook Concept
4+
sidebar_label: useEffect Hook
5+
sidebar_position: 2
6+
tags: [react, create-react-app, useEffect, hooks, react-scripts, react-dom, react-app]
7+
---
8+
9+
### useEffect
10+
11+
**Explanation:**
12+
`useEffect` is used to perform side effects in function components. Side effects include data fetching, subscriptions, or manually changing the DOM. In class components, side effects were managed in lifecycle methods like `componentDidMount`, `componentDidUpdate`, and `componentWillUnmount`.
13+
14+
When you call `useEffect`, you pass it a function that contains the code for your side effect. This function runs after every render by default. You can also provide a dependency array (`[]`) to control when the effect runs based on changes in state or props.
15+
16+
**Example:**
17+
```jsx
18+
import React, { useState, useEffect } from 'react';
19+
20+
function Timer() {
21+
const [seconds, setSeconds] = useState(0);
22+
23+
useEffect(() => {
24+
// This function runs after every render
25+
const interval = setInterval(() => {
26+
// Update 'seconds' every 1000ms (1 second)
27+
setSeconds(seconds => seconds + 1);
28+
}, 1000);
29+
30+
// Return a cleanup function to clear the interval
31+
return () => clearInterval(interval);
32+
}, []); // Empty array means effect runs only on mount and unmount
33+
34+
return (
35+
<div>
36+
<p>Timer: {seconds} seconds</p>
37+
</div>
38+
);
39+
}
40+
```
41+
42+
In this example, `useEffect` is used to create a timer that updates the `seconds` state every second (`1000ms`). The cleanup function returned by `useEffect` clears the interval when the component unmounts or when `seconds` changes due to a dependency array (`[]`) change.

docs/react/hooks/useMemo.md

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
---
2+
id: useMemo hook
3+
title: useMemo Hook Concept
4+
sidebar_label: useMemo Hook
5+
sidebar_position: 6
6+
tags: [react, create-react-app, useMemo, hooks, react-scripts, react-dom, react-app]
7+
---
8+
9+
### useMemo
10+
11+
**Explanation:**
12+
`useMemo` is used to memoize expensive calculations or computations so that they are only recomputed when necessary. It is similar to `useCallback`, but instead of memoizing functions, it memoizes the result of a computation.
13+
14+
When you call `useMemo`, you pass it a function that performs the expensive computation and a dependency array. It returns the memoized value that only changes when one of the dependencies has changed.
15+
16+
**Example:**
17+
```jsx
18+
import React, { useMemo, useState } from 'react';
19+
20+
function MemoizedFactorial() {
21+
const [number, setNumber] = useState(5);
22+
23+
// Memoize factorial calculation to optimize performance
24+
const factorial = useMemo(() => {
25+
let fact = 1;
26+
for (let i = 1; i <= number; i++) {
27+
fact *= i;
28+
}
29+
return fact;
30+
}, [number]);
31+
32+
return (
33+
<div>
34+
<p>Factorial of {number} is: {factorial}</p>
35+
{/* Input updates 'number' to recompute factorial */}
36+
<input type="number" value={number} onChange={(e) => setNumber(Number(e.target.value))} />
37+
</div>
38+
);
39+
}
40+
```
41+
42+
In this example, `useMemo` memoizes the `factorial` calculation based on the `number` state. It ensures that the factorial computation is only recalculated when `number` changes, optimizing performance by avoiding unnecessary computations on each render.

docs/react/hooks/useReducer.md

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
---
2+
id: useReducer hook
3+
title: useReducer Hook Concept
4+
sidebar_label: useReducer Hook
5+
sidebar_position: 4
6+
tags: [react, create-react-app, useReducer, hooks, react-scripts, react-dom, react-app]
7+
---
8+
9+
### useReducer
10+
11+
**Explanation:**
12+
`useReducer` is an alternative to `useState` for managing complex state logic within a component. It is often preferable when you have state transitions that involve multiple sub-values or when the next state depends on the previous one.
13+
14+
When you call `useReducer`, you pass it a reducer function and an initial state. It returns an array with the current state (`state`) and a dispatch function (`dispatch`) to trigger state updates based on action objects.
15+
16+
**Example:**
17+
```jsx
18+
import React, { useReducer } from 'react';
19+
20+
// Initial state with a 'count' property initialized to 0
21+
const initialState = { count: 0 };
22+
23+
// Reducer function defines how state updates in response to actions
24+
function reducer(state, action) {
25+
switch (action.type) {
26+
case 'increment':
27+
return { count: state.count + 1 }; // Increment 'count'
28+
case 'decrement':
29+
return { count: state.count - 1 }; // Decrement 'count'
30+
default:
31+
throw new Error(); // Throw an error for unknown actions
32+
}
33+
}
34+
35+
function Counter() {
36+
// Use 'useReducer' with 'reducer' function and 'initialState'
37+
const [state, dispatch] = useReducer(reducer, initialState);
38+
39+
return (
40+
<div>
41+
<p>Count: {state.count}</p>
42+
{/* Buttons dispatch 'increment' and 'decrement' actions */}
43+
<button onClick={() => dispatch({ type: 'increment' })}>Increment</button>
44+
<button onClick={() => dispatch({ type: 'decrement' })}>Decrement</button>
45+
</div>
46+
);
47+
}
48+
```
49+
50+
In this example, `useReducer` manages state updates for `count`. `dispatch` is used to trigger actions (`{ type: 'increment' }` or `{ type: 'decrement' }`), which are processed by the `reducer` function to compute the next state.

docs/react/hooks/useRef.md

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
---
2+
id: useRef hook
3+
title: useRef Hook Concept
4+
sidebar_label: useRef Hook
5+
sidebar_position: 7
6+
tags: [react, create-react-app, useRef, hooks, react-scripts, react-dom, react-app]
7+
---
8+
9+
### useRef
10+
11+
**Explanation:**
12+
`useRef` is used to maintain mutable references to elements or values across renders without triggering a re-render. It's particularly useful for accessing the DOM elements directly or storing any mutable value that persists for the entire lifetime of the component.
13+
14+
When you call `useRef`, it returns a mutable `ref` object whose `.current` property is initialized to the passed argument (`null` in the absence of an argument). This property can hold any mutable value.
15+
16+
**Example:**
17+
```jsx
18+
import React, { useRef } from 'react';
19+
20+
function FocusInput() {
21+
// Create a 'ref' object initialized to 'null'
22+
const inputRef = useRef(null);
23+
24+
// Function to focus on the input element
25+
const handleClick = () => {
26+
inputRef.current.focus(); // Access and focus the input element
27+
};
28+
29+
return (
30+
<div>
31+
{/* Assign 'inputRef' to the input element */}
32+
<input ref={inputRef}
33+
34+
type="text" />
35+
{/* Button uses 'handleClick' function to focus on input */}
36+
<button onClick={handleClick}>Focus Input</button>
37+
</div>
38+
);
39+
}
40+
```
41+
42+
In this example, `useRef` is used to create a reference (`inputRef`) to the input element. When the button is clicked, `handleClick` function accesses `inputRef.current` to focus on the input element without causing a re-render of the component.

docs/react/hooks/useState-hook.md

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
---
2+
id: useState hook
3+
title: useState Hook Concept
4+
sidebar_label: useState Hook
5+
sidebar_position: 1
6+
tags: [react, create-react-app, useState, hooks, react-scripts, react-dom, react-app]
7+
---
8+
### useState
9+
10+
**Explanation:**
11+
`useState` is a fundamental hook in React that allows functional components to manage state. State refers to data that changes over time and causes a component to rerender when updated. Prior to hooks, state management was exclusive to class components using `this.state`.
12+
13+
When you call `useState(initialState)`, it returns an array with two elements:
14+
- The current state (`count` in our example).
15+
- A function (`setCount`) that allows you to update the state.
16+
17+
**Example:**
18+
```jsx
19+
import React, { useState } from 'react';
20+
21+
function Counter() {
22+
// Declare a state variable named 'count' initialized to 0
23+
const [count, setCount] = useState(0);
24+
25+
return (
26+
<div>
27+
<p>You clicked {count} times</p>
28+
{/* On button click, update 'count' using 'setCount' */}
29+
<button onClick={() => setCount(count + 1)}>
30+
Click me
31+
</button>
32+
</div>
33+
);
34+
}
35+
```
36+
37+
In this example, `count` is the state variable initialized to 0, and `setCount` is the function used to update `count`. When the button is clicked, `setCount` is called with the new value of `count + 1`, causing the component to rerender with the updated count displayed.

0 commit comments

Comments
 (0)