Logo

dev-resources.site

for different kinds of informations.

Hooks in React

Published at
12/18/2023
Categories
react
hook
frontend
javascript
Author
izmroen
Categories
4 categories in total
react
open
hook
open
frontend
open
javascript
open
Author
7 person written this
izmroen
open
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.

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

🔸 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. 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
hook Article's
30 articles in total
Favicon
Share the state of a hook between components
Favicon
Understanding Hooks in the Phoenix Framework
Favicon
React Hooks: A Detailed Explanation
Favicon
Reusable React Hook Form
Favicon
Client side Git hooks 101
Favicon
React Hooks
Favicon
How not to useEffect
Favicon
Understanding useContext Hooks in React – An introduction and a Comprehensive Guide for Web Developers
Favicon
Understanding useState Hook in React – An introduction and a Comprehensive Guide for Web Developers
Favicon
Understanding useEffect Hooks in React – An introduction and Comprehensive Guide for Web Developers
Favicon
React 18 hooks
Favicon
Reusable Code: React Custom Hooks Guide
Favicon
React Usecallback for Kids/Beginners
Favicon
Optimizing Event Handlers in React using useCallback
Favicon
Understanding the useState Hook in React
Favicon
Implement refetch with axis
Favicon
Handle component state using local storage: useLocalStorage with Typescript
Favicon
Skills of writing unit test for react
Favicon
The practice of using Microsoft OAuth in the React hook
Favicon
Hooks in React
Favicon
A Guide to Building Custom Hooks in React
Favicon
A Guide to React Custom Hooks
Favicon
React Performance Booster - Introduction to the useMemo hook
Favicon
Mastering LocalStorage Management with React Hooks
Favicon
React Custom Hooks that can take props, but not always, what to do in TypeScript?
Favicon
useLocation Hook in React Router
Favicon
useLocation Hook in React Router
Favicon
Building a Custom React Hook: useIsAppOffline
Favicon
useLongPress Custom Hook
Favicon
Renderprops vs Custom Hooks: Which one to use?

Featured ones: