Skip to content

[Feature]: React Add the Hook concept Added #1323

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions docs/react/hooks/_category_.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"label": "Hooks",
"position": 5,
"link": {
"type": "generated-index",
"description": "5 minutes to learn the most important RoadMap for React Mastery."
}
}
37 changes: 37 additions & 0 deletions docs/react/hooks/useCallback.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
---
id: useCallback hook
title: useCallback Hook Concept
sidebar_label: useCallback Hook
sidebar_position: 5
tags: [react, create-react-app, useCallback, hooks, react-scripts, react-dom, react-app]
---
### useCallback

**Explanation:**
`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.

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.

**Example:**
```jsx
import React, { useState, useCallback } from 'react';

function MemoizedCounter() {
const [count, setCount] = useState(0);

// Memoize 'increment' function to prevent unnecessary renders
const increment = useCallback(() => {
setCount(count + 1);
}, [count]);

return (
<div>
<p>Count: {count}</p>
{/* Button uses memoized 'increment' function */}
<button onClick={increment}>Increment</button>
</div>
);
}
```

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.
31 changes: 31 additions & 0 deletions docs/react/hooks/useContext.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
---
id: useContext hook
title: useContext Hook Concept
sidebar_label: useContext Hook
sidebar_position: 3
tags: [react, create-react-app, useContext, hooks, react-scripts, react-dom, react-app]
---

### useContext

**Explanation:**
`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.

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.

**Example:**
```jsx
import React, { useContext } from 'react';

// Create a context object with a default value ('light')
const ThemeContext = React.createContext('light');

function ThemeComponent() {
// Use 'useContext' to access the current theme value ('light')
const theme = useContext(ThemeContext);

return <p>Current theme: {theme}</p>;
}
```

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.
42 changes: 42 additions & 0 deletions docs/react/hooks/useEffect-hook.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
---
id: useEffect hook
title: useEffect Hook Concept
sidebar_label: useEffect Hook
sidebar_position: 2
tags: [react, create-react-app, useEffect, hooks, react-scripts, react-dom, react-app]
---

### useEffect

**Explanation:**
`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`.

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.

**Example:**
```jsx
import React, { useState, useEffect } from 'react';

function Timer() {
const [seconds, setSeconds] = useState(0);

useEffect(() => {
// This function runs after every render
const interval = setInterval(() => {
// Update 'seconds' every 1000ms (1 second)
setSeconds(seconds => seconds + 1);
}, 1000);

// Return a cleanup function to clear the interval
return () => clearInterval(interval);
}, []); // Empty array means effect runs only on mount and unmount

return (
<div>
<p>Timer: {seconds} seconds</p>
</div>
);
}
```

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.
42 changes: 42 additions & 0 deletions docs/react/hooks/useMemo.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
---
id: useMemo hook
title: useMemo Hook Concept
sidebar_label: useMemo Hook
sidebar_position: 6
tags: [react, create-react-app, useMemo, hooks, react-scripts, react-dom, react-app]
---

### useMemo

**Explanation:**
`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.

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.

**Example:**
```jsx
import React, { useMemo, useState } from 'react';

function MemoizedFactorial() {
const [number, setNumber] = useState(5);

// Memoize factorial calculation to optimize performance
const factorial = useMemo(() => {
let fact = 1;
for (let i = 1; i <= number; i++) {
fact *= i;
}
return fact;
}, [number]);

return (
<div>
<p>Factorial of {number} is: {factorial}</p>
{/* Input updates 'number' to recompute factorial */}
<input type="number" value={number} onChange={(e) => setNumber(Number(e.target.value))} />
</div>
);
}
```

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.
50 changes: 50 additions & 0 deletions docs/react/hooks/useReducer.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
---
id: useReducer hook
title: useReducer Hook Concept
sidebar_label: useReducer Hook
sidebar_position: 4
tags: [react, create-react-app, useReducer, hooks, react-scripts, react-dom, react-app]
---

### useReducer

**Explanation:**
`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.

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.

**Example:**
```jsx
import React, { useReducer } from 'react';

// Initial state with a 'count' property initialized to 0
const initialState = { count: 0 };

// Reducer function defines how state updates in response to actions
function reducer(state, action) {
switch (action.type) {
case 'increment':
return { count: state.count + 1 }; // Increment 'count'
case 'decrement':
return { count: state.count - 1 }; // Decrement 'count'
default:
throw new Error(); // Throw an error for unknown actions
}
}

function Counter() {
// Use 'useReducer' with 'reducer' function and 'initialState'
const [state, dispatch] = useReducer(reducer, initialState);

return (
<div>
<p>Count: {state.count}</p>
{/* Buttons dispatch 'increment' and 'decrement' actions */}
<button onClick={() => dispatch({ type: 'increment' })}>Increment</button>
<button onClick={() => dispatch({ type: 'decrement' })}>Decrement</button>
</div>
);
}
```

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.
42 changes: 42 additions & 0 deletions docs/react/hooks/useRef.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
---
id: useRef hook
title: useRef Hook Concept
sidebar_label: useRef Hook
sidebar_position: 7
tags: [react, create-react-app, useRef, hooks, react-scripts, react-dom, react-app]
---

### useRef

**Explanation:**
`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.

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.

**Example:**
```jsx
import React, { useRef } from 'react';

function FocusInput() {
// Create a 'ref' object initialized to 'null'
const inputRef = useRef(null);

// Function to focus on the input element
const handleClick = () => {
inputRef.current.focus(); // Access and focus the input element
};

return (
<div>
{/* Assign 'inputRef' to the input element */}
<input ref={inputRef}

type="text" />
{/* Button uses 'handleClick' function to focus on input */}
<button onClick={handleClick}>Focus Input</button>
</div>
);
}
```

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.
37 changes: 37 additions & 0 deletions docs/react/hooks/useState-hook.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
---
id: useState hook
title: useState Hook Concept
sidebar_label: useState Hook
sidebar_position: 1
tags: [react, create-react-app, useState, hooks, react-scripts, react-dom, react-app]
---
### useState

**Explanation:**
`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`.

When you call `useState(initialState)`, it returns an array with two elements:
- The current state (`count` in our example).
- A function (`setCount`) that allows you to update the state.

**Example:**
```jsx
import React, { useState } from 'react';

function Counter() {
// Declare a state variable named 'count' initialized to 0
const [count, setCount] = useState(0);

return (
<div>
<p>You clicked {count} times</p>
{/* On button click, update 'count' using 'setCount' */}
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
```

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.
Loading