Bases du développement web front-end
React Hooks Fishing for Simplicity in Function Components

React Hooks: Fishing for Simplicity in Function Components

Have you ever wished to handle component state and lifecycle methods in your functional components without going Class components route? Well, say hello to React Hooks! They allow you to do exactly this, and more. Let's dive in, shall we?

Simple as Hook, Line and Sinker

Ahoy mates, let's explore useState, one of the most basic hooks in React.js. This hook makes your functional components stateful. Don't believe it? Take a look.

import React, { useState } from 'react';
 
function HookedComponent() {
  const [count, setCount] = useState(0);
 
  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

Did you notice? With useState, we can declare a state variable count and the function to update it setCount. We can then update the state just like we usually do in class components. No constructor, no this.state or this.setState. Neat, isn't it?

Hooked on Effects

Great, we've landed statefulness. Now let's open the door to lifecycle methods with another frequently used hook, useEffect. With this hook, we can handle 'side effects' such as data fetching, subscriptions, or manual DOM manipulation. Here's an example of how useEffect can work as componentDidMount.

import React, { useState, useEffect } from 'react';
 
function HookedComponent() {
  const [data, setData] = useState([]);
 
  useEffect(() => { 
    fetch('https://api.example.com/data')
      .then(response => response.json())
      .then(data => setData(data));
  }, []);
 
  return (
    <ul>
      {data.map(item => (
        <li key={item.id}>{item.name}</li>
      ))}
    </ul>
  );
}

In this example, our useEffect function makes a call to our API as soon as the component is mounted. And the empty array [] at the end? It ensures that the effect only gets triggered on component mount and not on updates.

A Word to the Wise

React Hooks are a powerful feature that can simplify your development experience. But remember, all good things should be used responsibly. In particular, don't use Hooks inside loops, conditions, or nested functions. And always use them at the top level of your React functions. For further details, you know who you gonna call? (React Docs (opens in a new tab))

Wrapping it up

React Hooks. Not as complex as you imagined, right? With a shift in perspective, and a little practice, you'll catch onto using Hooks in no time. So take out your rod and bait, the water is perfect!

Category: Front-end