What are Hooks in React and How to Use Them

Tiempo de lectura: 3 minutos

The Hooks are one of the most important features introduced in React to facilitate the reuse of logic and simplify the development of components. They allow you to use React functionality such as state or lifecycle inside functional components without needing to use classes.

Lagarto hook react - Pexels

You will learn what Hooks are, why they exist and how to use the most important ones in this tutorial.

The Hooks are special functions that allow you to “hook into” internal characteristics of React from functional components. Before their introduction, only class-based components could handle state and lifecycle.

Thanks to Hooks, it is now possible:

Hooks always start with the word use, making them easily identifiable.

The Hooks were born to solve several common problems in React:

First, class-based components were more complex to understand and maintain.

Second, sharing logic between components used to require complicated patterns like Higher Order Components or Render Props.

Thirdly, the logic related to a single functionality was scattered across different methods of the lifecycle cycle.

The Hooks solve these problems by allowing you to organize the logic by functionality and not by the phase of the lifecycle cycle.

Before using them, it is essential to know their main rules.

Only functional components or custom Hooks can use Hooks.

Hooks must always be called at the top level of a component, never inside conditions, loops, or nested functions.

This rule ensures that React correctly controls the execution order.

The Hook useState allows adding state to a functional component.

Basic example:

import { useState } from "react"; function Contador() { const [contador, setContador] = useState(0); return ( <div> <p>{contador}</p> <button onClick={() => setContador(contador + 1)}> Incrementar </button> </div> ); } 

This Hook returns a value and a function that allows updating it.

The Hook useEffect allows executing side effects within a component. Some examples are:

Ejemplo:

import { useEffect, useState } from "react"; function Ejemplo() { const [contador, setContador] = useState(0); useEffect(() => { document.title = `Clicks: ${contador}`; }, [contador]); return ( <button onClick={() => setContador(contador + 1)}> Incrementar </button> ); } 

The second parameter is an array of dependencies. The effect is executed when any of them changes.

If the array is empty, the effect only runs when the component mounts.

useContext allows access to shared values between components without needing to manually pass props.

First, a context is created:

import { createContext } from "react"; export const ThemeContext = createContext(); 

Later it’s used inside a component:

import { useContext } from "react"; import { ThemeContext } from "./ThemeContext"; function Button() { const theme = useContext(ThemeContext); return ; } 

This Hook facilitates sharing global data such as visual themes, authenticated user, or configurations.

useRef allows storing values that persist between renders without causing a new render when changed.

Also used to access elements of the DOM directly.

Example:

import { useRef } from "react"; function InputFocus() { const inputRef = useRef(null); const enfocar = () => { inputRef.current.focus(); }; return ( <>    ); } 

Hook useMemo

useMemo allows to memorize expensive calculation results to improve performance.

Ejemplo:

import { useMemo } from "react"; function Calculo({ numero }) { const resultado = useMemo(() => { console.log("Calculando..."); return numero * 2; }, [numero]); return {resultado}

; }

The calculation only executes when the dependency changes.

useCallback remembers functions to prevent them from being recreated unnecessarily, which can improve performance in child components.

Example:

import { useCallback } from "react"; function Ejemplo({ onClick }) { const manejarClick = useCallback(() => { console.log("Click"); }, []); return ; } 

Custom Hooks

You can also create your own custom Hooks to reuse logic.

Example:

  import { useState } from "react";    function useContador(inicial = 0) {    const [valor, setValor] = useState(inicial);    const incrementar = () => setValor(valor + 1);    const decrementar = () => setValor(valor - 1);    return { valor, incrementar, decrementar };  }

Hook Usage:

  function App() {    const { valor, incrementar } = useContador();    return (      

{valor}

); }

Leave a Comment