Hooks in React
Tags: react, hook, frontend, javascript
Published: 2023-12-18 19:21:47

### 1 Definitions :
To explain the concept of **hooks** in React, it is important to start by explaining the terms below :

> - ✔️**A React component** is a function that renders an HTML element. React components can be either <u>classes</u> or <u>functions</u>.

> - ✔️**React classes** <u>class components</u>) use the React lifecycle to manage state and component events.

> - ✔️**The React lifecycle** is a set of events that occur during the life of a React component. Lifecycle events allow developers to interact with the React component at different points in its life.

> - ✔️**React functions** (<u>functions components</u>) use **hooks** to manage state and component events.

### 2. What is a Hook?

> - **Hooks** are functions that allow developers to manage state and access React lifecycle features <u>without</u> having to write a class.

To explain hooks, we can use the following analogy:

> - <u>**React classes**</u> are like washing machines. They have a life cycle that allows them to wash the laundry.

> - <u>**React functions**</u> are like washing machines without a lifecycle. They must be used with specific tools for washing laundry.

**Hooks** are these specific tools ⚙️ They allow React functions to access React lifecycle features.

**🔸 The UseState() Hook:**
- **The useState() Hook** : Allows you to manage the state of a React component.

```
function App() {
    const [number, setNumber] = useState(0);
 
    return (
       <div>
          <h1>Number: [number)</h1>
          <button onClick={() => setNumber(number+ 1)}>+1</button>
       </div>
    );
 }
```

This React component uses the **useState()** hook to manage the state of the number . The number variable represents the current state of the number. The **setNumber()** function allows you to modify the state of the number . 

➡️The **useState()** hook returns 2 values : <u>**the current value**</u> of the state & a <u>**function**</u> that allows to modify the state.

📌There are many hooks available, each with their own purpose.

🗃️Here are some of the most common hooks:

> • **useState():** Allows you to manage the state of a React component. 
> • **useEffect():** Allows you to react to changes in the environment of a React component.
> • **useContext():** Allows access to a context from a React component. 
> • **useReducer():** Allows you to manage a complex state of a React component. 
> • **useParams()** …..etc

**🔸 The UseEffect() Hook:**

**The useEffect() Hook** allows a React component to perform actions at specific times and when certain properties or state change. It is useful for carrying out side effects, such as:

> 1. <u>Data fetching</u>
> 2. <u>Update the DOM</u>
> 3. <u>Add or remove event listeners</u>

`The useEffect() hook takes 2 arguments: from a function and an array of dependencies :`

```
useEffect(() => {
      // Code to execute after rendering the component
      // and after each update
   }, [dependency]);
```

> - ✔️The function is executed after the component is rendered and after each update. 
> - ✔️The dependency table allows you to specify the values ​​that should trigger execution of the function. If a value in the dependency array changes, the function is executed.

_Example of using the **useEffect()** hook to update the DOM:_

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

  useEffect(() => {
    document.title = `Count: ${count}`;
  }, [count]);

  return (
    <div>
      <h1>Count: {count}</h1>
      <button onClick={() => setCount(count + 1)}>+1</button>
    </div>
  );
}
```

In this example, the useEffect() hook is used to update the page title each time that the value of the **count** variable changes. This is because the **count** variable is included in the dependency table.

_Example of using the **useEffect()** hook to **<u>fetch</u>** data:_

```
function App() {
  const [users, setUsers] = useState([]);

  useEffect(() => {
    fetch('https://api.github.com/users')
      .then((response) => response.json())
      .then((data) => setUsers(data));
  }, []);

  return (
    <ul>
      {users.map((user) => (
        <li key={user.id}>{user.login}</li>
      ))}
    </ul>
  );
}

```

In this example, **the useEffect()** hook is used to perform data <u>fetching</u> from the GitHub API . The function is executed only once , after the initial rendering of the component. That is due to the dependency table being empty **[ ]** .

> - ✔️Hooks are a powerful way to manage state and side effects in React components. 
> - ✔️The **useEffect()** hook is particularly useful for performing asynchronous operations, such as data fetching.

_Example: Add or remove event-listeners_
It is possible to add or remove event listeners in a React component by using the useEffect() hook.

To add an event listener, simply use the **addEventListener()** function in the function of the **useEffect()** hook.

`The addEventListener() function takes two arguments: the event to listen for and the function to callback that will be called when the event occurs.`

```
window.removeEventListener(‘click’, handlclick]);

```
Here's an example of adding an event listener for a button click:

```
function App() {
  const [count, setCount] = useState(0);
  useEffect(() => {
    const button = document.getElementById('button');
    const handleClick = () => {
      setCount((prevCount) => prevCount + 1);
    };
    button.addEventListener('click', handleClick);
    return () => {
      // Cleanup the event listener when the component is unmounted
      button.removeEventListener('click', handleClick);
    };
  }, []);
  return (
    <div>
      <h1>Count: {count}</h1>
      <button id="button">+1</button>
    </div>
  );
}

```