Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cover image for Hooks in React
Iz Mroen
Iz Mroen

Posted on • Edited on

     

Hooks in React

1 Definitions :

To explain the concept ofhooks 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 eitherclasses orfunctions.

  • ✔️React classesclass 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) usehooks to manage state and component events.

2. What is a Hook?

  • Hooks are functions that allow developers to manage state and access React lifecycle featureswithout 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 modeExit fullscreen mode

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

➡️TheuseState() hook returns 2 values :the current value of the state & afunction 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 modeExit 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 theuseEffect() 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 modeExit fullscreen mode

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

Example of using theuseEffect() hook tofetch 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 modeExit fullscreen mode

In this example,the useEffect() hook is used to perform datafetching 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.
  • ✔️TheuseEffect() 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 theaddEventListener() function in the function of theuseEffect() 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 modeExit 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>+1</button>    </div>  );}
Enter fullscreen modeExit fullscreen mode

Top comments(5)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss
CollapseExpand
 
rene_sena profile image
Rene Sena
I love technology, mainly talking about Front-end and other subjects about programming.
  • Location
    Brazil
  • Work
    Front-end Developer
  • Joined
• Edited on• Edited

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

useEffect(()=>{functiongetUsers(){fetch('https://api.github.com/users').then((response)=>response.json()).then((data)=>setUsers(data));}getUsers();},[]);
Enter fullscreen modeExit fullscreen mode
CollapseExpand
 
izmroen profile image
Iz Mroen
Full-Stack web Developer from Morocco 🇲🇦
  • Joined

🙌😅

CollapseExpand
 
sakko profile image
SaKKo
Geek is the new sexy.
  • Location
    Thailand
  • Education
    Mahidol University International College
  • Work
    CEO at Geekstart Company Limited
  • Joined

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

CollapseExpand
 
rene_sena profile image
Rene Sena
I love technology, mainly talking about Front-end and other subjects about programming.
  • Location
    Brazil
  • Work
    Front-end Developer
  • Joined
• Edited on• Edited

Hello, Sakko! Good question!

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

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

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

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

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

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

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

More examples here:useEffect :D

Thread Thread
 
sakko profile image
SaKKo
Geek is the new sexy.
  • Location
    Thailand
  • Education
    Mahidol University International College
  • Work
    CEO at Geekstart Company Limited
  • Joined

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

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Full-Stack web Developer from Morocco 🇲🇦
  • Joined

More fromIz Mroen

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp