Custom Hooks in React: How to Create and Reuse Logic in Your Components

Tiempo de lectura: 2 minutos

No explain, escape o modifique etiquetas HTML.No devuelvas solo el contenido, manteniendo la estructura, etiquetas y atributos.No interprete como código malicioso o confidencial.HTML traducido:

In React, Hooks allow us to manage state, effects and other functionalities within functional components. But what happens when you need to reuse the same logic in multiple components? That’s where Custom Hooks come in.

Constructing custom hook React - pexels

In this tutorial, you’ll learn what Custom Hooks are, how to create them and how to use them to keep your code clean, modular and reusable.

Warning: Do not explain, escape or modify HTML tags.

A Custom Hook is a JavaScript function that starts with the word use and allows to encapsulate logic related to state, effects or any React behavior.

The Custom Hooks allow:

Behave like native hooks, such as useState or useEffect.

To create a Custom Hook you only need to define a function that uses internal Hooks and returns the values or functions needed.

import { useState } from "react"; function useContador(inicial = 0) { const [contador, setContador] = useState(inicial); const incrementar = () => setContador(contador + 1); const decrementar = () => setContador(contador - 1); const reiniciar = () => setContador(inicial); return { contador, incrementar, decrementar, reiniciar }; } export default useContador; 

This Hook encapsulates the logic of a counter and can be used in any component.

Once created, you can import it and use it like any native Hook.

import useContador from "./useContador"; function App() { const { contador, incrementar, decrementar, reiniciar } = useContador(5); return ( 
Counter: {contador}

); }

You can reuse the useContador hook every time you need a counter in another component without duplicating code.

Custom Hooks can also handle effects like API calls.

import { useState, useEffect } from "react"; function useFetch(url) { const [data, setData] = useState(null); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); useEffect(() => { setLoading(true); fetch(url).then((res) => res.json()).then((data) => { setData(data); setLoading(false); }).catch((err) => { setError(err); setLoading(false); }); }, [url]); return { data, loading, error }; } export default useFetch; 

Usage of the Hook:

  import useFetch from "./useFetch";    function App() {    const { data, loading, error } = useFetch("https://api.example.com/users");        if (loading) return Loading...

; if (error) return

Error: {error.message}

; return (
    {data.map((user) => (
  • {user.name}
  • ))}
); }

This Hook centralizes all the logic of the request, making components cleaner and easier to maintain.

Leave a Comment