DEV Community

Cover image for Hooks in React
Iz Mroen
Iz Mroen

Posted on

Hooks in React

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 classes or functions.

  • ✔️React classes class components) 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 (functions components) 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 without having to write a class.

To explain hooks, we can use the following analogy:

  • React classes are like washing machines. They have a life cycle that allows them to wash the laundry.

  • React functions 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.

- 🔸 Le Hook UseState() :

  • 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>
    );
 }
Enter fullscreen mode Exit fullscreen mode

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 : the current value of the state & a function 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

- 🔸 Le Hook UseEffect():

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. Data fetching
  2. Update the DOM
  3. Add or remove event listeners

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]);
Enter fullscreen mode Exit fullscreen mode
  • ✔️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>
  );
}
Enter fullscreen mode Exit fullscreen mode

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 fetch 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>
  );
}

Enter fullscreen mode Exit fullscreen mode

In this example, the useEffect() hook is used to perform data fetching 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]);

Enter fullscreen mode Exit fullscreen mode

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>
  );
}

Enter fullscreen mode Exit fullscreen mode

Top comments (5)

Collapse
 
rene_sena profile image
Rene Sena • Edited

Good explanation!
An observation about useEffect, it's recommended to create a function to "fetch" and after calling it. For example:

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

   getUsers();
  }, []);
Enter fullscreen mode Exit fullscreen mode
Collapse
 
izmroen profile image
Iz Mroen

🙌😅

Collapse
 
sakko profile image
SaKKo

sorry, but can you help me explain how is it better? I never know this. thank you in advance

Collapse
 
rene_sena profile image
Rene Sena • Edited

Hello, Sakko! Good question!

The official React documentation does not explicitly specify that you should define a function within the useEffect and then call it. However, it does provide examples and guidance on how to use useEffect, including fetching data.

The reason why many developers choose to define a function within the useEffect and then call it is due to an ESLint rule called react-hooks/exhaustive-deps. This rule requires that all functions called within a useEffect be included in the useEffect dependencies or be defined within the useEffect itself.

If you try to use an asynchronous function directly within the useEffect, as in the example below:

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

You will see a warning from ESLint, because asynchronous functions implicitly return a promise, and the functions passed to useEffect should not return anything other than a cleanup function or nothing.

Therefore, the recommended approach is to define the asynchronous function within the useEffect and then call it:

useEffect(() => {
  const getUsers = async () => await fetch('https://api.github.com/users')
      .then((response) => response.json())
      .then((data) => setUsers(data));

  getUsers();
}, []);
Enter fullscreen mode Exit fullscreen mode

More examples here: useEffect :D

Thread Thread
 
sakko profile image
SaKKo

oh wow, thank you so much. i love your answer.