You don't have access to this class

Keep learning! Join and start boosting your career

Aprovecha el precio especial y haz tu profesi贸n a prueba de IA

Antes: $249

Currency
$209
Suscr铆bete

Termina en:

2 D铆as
19 Hrs
36 Min
47 Seg
Curso de React Avanzado

Curso de React Avanzado

Estefany Aguilar

Estefany Aguilar

C贸mo utilizar Custom Hooks en React

6/31
Resources

What are Custom Hooks in React?

Custom Hooks are a powerful and flexible feature of React that allows you to reuse logic in function components. They do not completely replace higher-order components (HOCs), but they offer a simpler and more straightforward way to manage shared logic. In essence, Custom Hooks allow you to extract logic from the component and reuse it in multiple places in the project.

How to create a Custom Hook?

Creating a Custom Hook is as simple as defining a function in JavaScript that uses other React hooks. Custom Hooks begin with the word "use", which is an important convention to ensure that their operation is consistent with built-in React hooks such as useState or useEffect.

import { useState, useEffect } from 'react';
function useCustomHook() { // Define some internal state const [state, setState] = useState(initialValue);
 // Side effects useEffect((() => { // logic for effects }, [state]);
 // Return values or functions return [state, setState];}

When is a Custom Hook useful?

They are particularly useful in several situations:

  • Logic reuse: You can extract and reuse state logic or common effects across multiple components.
  • Separation of responsibilities: You keep your components clean and focused on rendering UI, and Custom Hooks handle the logic.
  • Abstraction of complexity: They allow you to encapsulate complex logic in a simple API.

Comparison between Custom Hooks and Higher-order Components

It is natural to ask whether Custom Hooks replace higher-order components (HOCs). The short answer is no; each has its place and specific advantages.

When to use Custom Hooks?

  • Simplicity: When the logic is primarily state or effect handling, Custom Hooks are simpler and more straightforward.
  • Less overhead: You don't need to wrap your component, which can simplify the code structure.
  • Ease of reading: The code structure is usually clearer when using hooks, as it avoids the need to read multiple layers of components.

When to prefer Higher-order Components?

  • Require props manipulation: When you need to inject or modify input properties extensively.
  • Non-hooks logic: When the logic does not quite fit into the hooks paradigm or relies on advanced component tree manipulation.

Practical examples of use

1. Custom Hook to detect window events

Suppose you need to detect window resizing events in multiple components. This can be achieved with a custom Hook.

import { useState, useEffect } from 'react';
function useWindowWidth() { const [width, setWidth] = useState(window.innerWidth);
 useEffect(() => { const handleResize = () => setWidth(window.innerWidth);
 window.addEventListener('resize', handleResize); return () => window.removeEventListener('resize', handleResize); }, []);
 return width;}
// Use in a componentfunction MyComponent() { const width = useWindowWidth();
 return <div>Window  width: {width}</div>;}

2. Custom Hook to manage user authentication.

Imagine you have logic for authenticating users that you need to reuse in multiple parts of your application.

function useAuth() { const [isAuthenticated, setIsAuthenticated] = useState(false);
 const login = () => setIsAuthenticated(true); const logout = () => setIsAuthenticated(false);

 return { isAuthenticated, login, logout };}
// Use in a componentfunction AuthButton() { const { isAuthenticated, login, logout } = useAuth();
 return ( <div> <button onClick={isAuthenticated ? logout : login}> {isAuthenticated ? 'Logout' : 'Login'} </button>  </div> </div> );}

Final thoughts on Custom Hooks.

In the React ecosystem, Custom Hooks represent a significant move towards cleaner, more maintainable and easier to understand code. They offer a modern approach to solving long-standing problems related to logic reuse. Understanding and effectively implementing Custom Hooks will allow you to write more efficient and scalable code. So don't hesitate to experience them and see how they can transform your React projects.

Also, the development world keeps moving forward, and with each new project, there are opportunities to refine your skills and explore new tools and patterns. Always stay curious and open to continuous learning - the development journey never ceases to amaze!

Contributions 4

Questions 1

Sort by:

Want to see more contributions, questions and answers from the community?

Los Custom Hooks en React son funciones que permiten reutilizar l贸gica de estado y efectos entre componentes. No reemplazan a los Higher-Order Components (HOCs), sino que ofrecen una forma m谩s sencilla y elegante de gestionar la reutilizaci贸n de c贸digo. Al crear un Custom Hook, puedes encapsular l贸gica que puede ser compartida entre m煤ltiples componentes, facilitando la mantenibilidad y la organizaci贸n del c贸digo. Su uso es ideal para manejar funcionalidades espec铆ficas sin complicar la jerarqu铆a de componentes.
En este caso, cual seria la diferencia entre utilizar el hook de useState con el custom hook useLoading ? ya que el comportamiento que tiene es el mismo que haces con useState
Los Custom Hooks son utiles extraer la logica de los componente y mantenerlos mas limpios ademas de poder reutilizar la logica en varios sectores de la aplicacion. Un ejemplo claro es cuando realizamos fetching de datos: ```js import { useState, useEffect } from "react"; import axios from "axios"; function useFetch(url) { const [data, setData] = useState(null); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); useEffect(() => { let isMounted = true; // Para evitar problemas si el componente se desmonta axios .get(url) .then((response) => { if (isMounted) { setData(response.data); setLoading(false); } }) .catch((err) => { if (isMounted) { setError(err); setLoading(false); } }); return () => { isMounted = false; // Cleanup }; }, [url]); return { data, loading, error }; } // Uso del hook function App() { const { data, loading, error } = useFetch("https://jsonplaceholder.typicode.com/posts"); if (loading) return

Cargando...

; if (error) return

Error: {error.message}

; return (
    {data.map((post) => (
  • {post.title}
  • ))}
); } ```Tambien pueden ser utililes para manejo de formularios, animaciones, cuando necesitamos sabes ancho y alto de la pantalla etc.
Para crear un `useState` sin usar los hooks de React, puedes implementar una funci贸n simple en JavaScript que mantenga el estado. Aqu铆 tienes un ejemplo: ```javascript function createState(initialValue) { let state = initialValue; const setState = (newValue) => { state = newValue; }; return [() => state, setState]; } // Uso const [getState, setState] = createState(0); console.log(getState()); // 0 setState(5); console.log(getState()); // 5 ``` Esta implementaci贸n permite obtener y actualizar el estado de forma similar a `useState`, pero sin la funcionalidad completa de React.