A veces, 5 minutos es todo lo que tienes. Entonces, en este artículo, solo vamos a tocar dos de los ganchos más utilizados en React: useState
y useEffect
.
Si no está familiarizado con los ganchos, aquí está el TL; DR: debido a los ganchos, casi no hay necesidad de componentes basados en clases. Los enganches le permiten "conectarse" al ciclo de vida subyacente y los cambios de estado de un componente dentro de un componente funcional. Más que eso, a menudo también mejoran la legibilidad y la organización de sus componentes.
Si desea una introducción adecuada a este tema, puede unirse a la lista de espera para mi próximo curso avanzado de React, o si todavía es un principiante, consulte mi curso introductorio sobre React.
useState
Comencemos con un componente funcional.
import React from 'react'; function App() { return ( 0
Change! ); }
Como puede ver, nada lujoso en este momento. Solo estamos renderizando texto y un botón (inútil).
Ahora importemos nuestro primer gancho, useState
para aprender cómo manejar el estado en nuestro componente funcional.
Como este gancho es una función, veamos console.log
lo que obtenemos de él.
import React, { useState } from 'react'; function App() { const value = useState(); console.log(value); return ( 0
Change! ); }
En la consola, obtenemos una matriz
> [null, ƒ()]
Y cuando pasamos un argumento a useState
const value = useState(true);
En la consola, obtenemos una matriz con nuestro valor como primer miembro.
> [true, ƒ()]
Ahora, en nuestro componente, podemos acceder a nuestro estado en value[0]
y representarlo en
en lugar de un valor codificado.
import React, { useState } from 'react'; function App() { const value = useState(0); console.log(value); // [0, ƒ()] return ( {value[0]}
Change! ); }
Podemos mejorar nuestro código usando la desestructuración de matrices para almacenar el valor del useState
gancho. Es similar a la desestructuración de objetos, que tiende a ser algo más común. En caso de que no esté muy familiarizado con la desestructuración de objetos, aquí hay un resumen rápido:
const person = { name: 'Joe', age: 42 }; // creates 2 const values from person object const { name, age } = person; console.log(name); // 'Joe' console.log(age); // 42
La destrucción de matrices es casi lo mismo, pero utiliza corchetes en []
lugar de llaves {}
.
Un consejo rápido: en la desestructuración de objetos, los nombres de las variables creadas deben coincidir con los nombres de las propiedades del objeto. Para la desestructuración de matrices, ese no es el caso. Todo se trata del orden. El beneficio aquí es que podemos nombrar los elementos como queramos.
Usando la desestructuración de matrices, podemos obtener el valor inicial de estado del useState()
gancho.
import React, { useState } from 'react'; function App() { // remember, there's a second item from the array that's missing here, but we'll come right back to use it soon const [count] = useState(0); return ( {count}
Change! ); }
Bien, tenemos el valor del estado inicial. ¿Cómo cambiamos el valor en el estado con ganchos?
Recuerde que useState()
hook devuelve una matriz con 2 miembros. ¡El segundo miembro es una función que actualiza el estado!
const [count, setCount] = useState(0);
You can, of course, call it what you wish, but by convention, it's normally called with prefix "set-", and then whatever state variable we wish to update was called, so setCount
it is.
It's simple to use this function. Just call it and pass the new value you want that state to have! Or, just like this.setState
in a class component, you can pass a function that receives the old state and returns the new state. Rule of thumb: do this anytime you need to rely on the past state to determine the new state.
To call it, we'll pass it to the onClick
event listener. And just like with a regular setState
in a class-based component, we can pass our state update to setCount
.
function App() { const [count, setCount] = useState(0); return ( {count}
setCount(prevCount => prevCount + 1)}> Change! ); }
We can clean this up a bit, by extracting our state update to a separate function.
function App() { const [count, setCount] = useState(0); function change() { setCount(prevCount => prevCount + 1); } return ( {count}
Change! ); }
Great! And now when we can see the counter going up when we click the button.
Of course, useState
can get a lot more complicated than this, but we've only got 5 minutes here, so let's move on to the next hook for now.
useEffect
Hooks have simplified quite a few things, compared to the way things were in class-based components. Previously we needed to know a bit about lifecycle methods and which one is best suited for which situation. useEffect
hook simplified this situation. If you wish to perform side effects, network request, manual DOM manipulation, event listeners or timeouts and intervals.
useEffect
hook can be imported just like useState
.
import React, { useState, useEffect } from 'react';
To make useEffect
do something, we pass it an anonymous function as an argument. Whenever React re-renders this component, it will run the function we pass to useEffect
.
useEffect(() => { /* any update can happen here */ });
This is what the whole code might look like.
import React, { useState, useEffect } from 'react'; function App() { const [count, setCount] = useState(0); function change() { setCount(prevCount => prevCount + 1); } useEffect(() => { /* any update can happen here */ }); return ( {count}
Change! ); } export default App;
As an example, we will use a nice npm
package that generates a random color. Feel free to write your own if you wish of course, but for this tutorial, we will just install it, npm i randomcolor
, and import.
import randomcolor from 'randomcolor';
Let's now use our knowledge about useState
hook to store some random color in the state.
const [color, setColor] = useState(''); // initial value can be an empty string
We then can then assign the color of the counter we already have.
{count}
Now, just for the sake of it, let's change the color of the counter on every click of the Change!
button. useEffect
will run every time the component re-renders, and the component will re-render every time the state is changed.
So if we write the following code, it would get us stuck in an infinite loop! This is a very common gotcha with useEffect
useEffect(() => { setColor(randomcolor()); });
setColor
updates state, which re-renders the component, which calls useEffect
, which runs setColor
to update the state, which re-renders the component... Yikes!
We probably only want to run this useEffect
when the count
variable changes.
To tell useEffect
which variable(s) to keep track of, we give an array of such variables as a second argument.
useEffect(() => { setColor(randomcolor()); }, [count]);
Esto básicamente dice "sólo ejecuta este efecto sicount
cambia el estado. De esta manera podemos cambiar el color y no hacer que nuestro efecto se ejecute infinitamente".
Conclusión
Hay mucho más que aprender sobre los ganchos, pero espero que hayas disfrutado de este rápido vistazo de 5 minutos a los ganchos.
Para obtener más información sobre React Hooks y otras excelentes funciones de React, puede unirse a la lista de espera para mi próximo curso avanzado de React. O si está buscando un amigable para principiantes, puede consultar mi curso introductorio sobre React.
¿Feliz codificación?