Patrones de renderizado y composici贸n
Por qu茅 debes aprender React Avanzado
C贸mo implementar Render Props y Composition en React
C贸mo implementar Control Props en React
C贸mo implementar el Patr贸n Compound en React
Qu茅 son los High-Order Components en React
C贸mo utilizar Custom Hooks en React
C贸mo implementar el Patr贸n Container-Presenter en React
React: Diferencias entre componentes controlados y no controlados
Navegaci贸n con React Router
Qu茅 es Single Page Application y Server Side Rendering en React
Enrutamiento din谩mico y navegaci贸n program谩tica en React
Optimizaci贸n con Rutas Anidadas y Lazy Loading en React
Rutas Protegidas, Redirecciones y Manejo de Errores
Manejo del estado en React
React Context y Patr贸n Provider
React Context y Custom Hooks
useReducer: Store
useReducer: Actions y Reducers
useReducer: Componente Todo List
Redux Toolkit: Store y Actions
Redux Toolkit: Reducer
Redux Toolkit: Componente Todo List
Zustand: Configuraci贸n del Store
Zustand: Componente Todo List
State Machines
State Machines: configuraci贸n
State Machines: componente Wizard
State Machines: XState Visualizer
Comunicaci贸n con servidor y data fetching
Qu茅 es TanStack Query
Code Splitting y Manejo de Errores
Paginaci贸n con Concurrent Mode y useTransition
Memoizaci贸n y Lazy Loading con Suspense
Sigue avanzando con tus conocimientos de React
Nunca pares de aprender React
You don't have access to this class
Keep learning! Join and start boosting your career
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.
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];}
They are particularly useful in several situations:
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.
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>;}
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> );}
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
Cargando...
; if (error) returnError: {error.message}
; return (
Want to see more contributions, questions and answers from the community?