Aprende todo un fin de semana sin pagar una suscripción 🔥

Regístrate

Comienza en:

02D

04H

56M

42S

1

React Hooks Intro [EN][ES]

Hooks are available from React version 16.8 and ahead, it is recommended to use hooks for new projects. What they solve? Well, the usage of classes to create components create a big complexity for the developer. Also, the binding among components can be confused to understand. It is recommended to not rush, but learn about Hooks and how can you make your own ones.

Here questions people do about Hooks —> Click me

UseState -click me for official info-

This feature from React let us establish state and set them locally in a component without the need of a class. This means if you have a function and then realize you need to add a state you can do it using useState Hooks.

How does this work? well, useState returns an array of two elements, this is the state and the function that updates it. So it is recommendable to declare a constant inside the function, destructuring an array. Where the first variable will keep the state value and the second the function’s name that will update the state.

With this hook, we are imitating the behavior of this.state and setState in-class components. You can create as many constants as states you may see necessary.

1:  import React, { useState } from'react'; 2:
 3:  functionExample() {
 4:    const [count, setCount] = useState(0); 5:
 6:    return (
 7:      <div>
 8:        <p>You clicked {count} times</p>
 9:        <buttononClick={() => setCount(count + 1)}>10:         Click me
11:        </button>
12:      </div>13:    );
14:  }

UseEffect -click me for official info-

As the hook says the “effect” after a component to render is what you want to specify, normally these are “side-effects” like API request, managing the DOM, etc. This hook must be called inside the component, so it can take properties or states needed for the update. Have in mind useEffect will be applied after each renders so in case you want to clean up the parameter function of the hook has to return a function. A case of clean up the effect is when you want to unsubscribe a component. To optimize the re-render and skip with the previous state or prop when they are the same as the updated value, then we pass an array as the second argument with those variables as elements.

Basically, useEffect is the combination of componentDidMount, componentDidUpdate and componentWillUnmount.

// No cleanupfunctionExample() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    document.title = `You clicked ${count} times`;
  });
}
// Cleanup
useEffect(() => {
    functionhandleStatusChange(status) {
      setIsOnline(status.isOnline);
    }

    ChatAPI.subscribeToFriendStatus(props.friend.id, handleStatusChange);
    return () => {
      ChatAPI.unsubscribeFromFriendStatus(props.friend.id, handleStatusChange);
    };
  });

Here also a good tip for using useEffect when subscribing and unsubscribing in each render.

// Mount with { friend: { id: 100 } } props
ChatAPI.subscribeToFriendStatus(100, handleStatusChange);     // Run first effect// Update with { friend: { id: 200 } } props
ChatAPI.unsubscribeFromFriendStatus(100, handleStatusChange); // Clean up previous effect
ChatAPI.subscribeToFriendStatus(200, handleStatusChange);     // Run next effect// Update with { friend: { id: 300 } } props
ChatAPI.unsubscribeFromFriendStatus(200, handleStatusChange); // Clean up previous effect
ChatAPI.subscribeToFriendStatus(300, handleStatusChange);     // Run next effect// Unmount
ChatAPI.unsubscribeFromFriendStatus(300, handleStatusChange); // Clean up last effect

Hooks Rules

In order to work with Hooks, we have to keep in mind that we can not call hooks inside javaScript functions like for example event handlers likewise using them inside Conditionals, loops, or nested functions.

React team offers a plugin to follow these rules automatically, Here the link

[ES]

  • Los ganchos están disponibles a partir de la versión 16.8 de React en adelante, se recomienda usar ganchos para nuevos proyectos. ¿Qué resuelven? Bueno, el uso de clases para crear componentes crea una gran complejidad para el desarrollador. Además, la unión entre componentes se puede confundir para comprender. Se recomienda no apresurarse, pero aprender sobre Hooks y cómo puede hacer los suyos propios. *

Aquí las preguntas que la gente hace sobre Hooks -> [Click me] (https://reactjs.org/docs/hooks-faq.html)

UseState [- * haz clic en mí para obtener información oficial- *] (https://reactjs.org/docs/hooks-state.html)

Esta característica de React nos permite establecer el estado y configurarlo localmente en un componente sin la necesidad de una clase. Esto significa que si tiene una función y luego se da cuenta de que necesita agregar un estado, puede hacerlo usando useState Hooks.

¿Como funciona esto? bueno, useState devuelve una matriz de dos elementos, este es el estado y la función que lo actualiza. Por lo que es recomendable declarar una constante dentro de la función, desestructurando una matriz. Donde la primera variable mantendrá el valor del estado y la segunda el nombre de la función que actualizará el estado.

Con este gancho, estamos imitando el comportamiento de los componentes de clase this.state y setState. Puede crear tantas constantes como estados considere necesarios.

`` jsx
1: importar React, {useState} desde ‘reaccionar’; 2:
3: Ejemplo de función () {
4: const [count, setCount] = useState (0); 5:
6: retorno (
7: <div>
8: <p> Hiciste clic {count} veces </p>
9: <button onClick = {() => setCount (count + 1)}> 10: Click me
11: </button>
12: </div>
13:);
14:}
’’

UseEffect [- * haz clic en mí para obtener información oficial- *] (https://reactjs.org/docs/hooks-effect.html)

Como dice el gancho, el “efecto” después de un componente para renderizar es lo que desea especificar, normalmente estos son “efectos secundarios” como la solicitud de API, la gestión del DOM, etc. Este gancho debe llamarse dentro del componente, para que pueda tomar propiedades o estados necesarios para la actualización. Tenga en cuenta que useEffect se aplicará después de cada renderizado, por lo que, en caso de que desee limpiar la función de parámetro del gancho, debe devolver una función. Un caso de limpieza del efecto es cuando desea cancelar la suscripción de un componente. Para optimizar la re-renderización y saltar con el estado o prop anterior cuando son iguales que el valor actualizado, luego pasamos una matriz como segundo argumento con esas variables como elementos.

Básicamente, useEffect es la combinación de componentDidMount, componentDidUpdate y componentWillUnmount.

`` jsx
// Sin limpieza
función Ejemplo () {
const [cuenta, setCount] = useState (0);

useEffect (() => {
document.title = Ha hecho clic en $ {count} veces;
});
}
// Limpiar
useEffect (() => {
function handleStatusChange (estado) {
setIsOnline (status.isOnline);
}

ChatAPI.subscribeToFriendStatus (props.friend.id, handleStatusChange);
return () => {
  ChatAPI.unsubscribeFromFriendStatus (props.friend.id, handleStatusChange);
};

});
’’

Aquí también un buen consejo para usar useEffect al suscribirse y darse de baja en cada render.

`` jsx
// Montar con {friend: {id: 100}} accesorios
ChatAPI.subscribeToFriendStatus (100, handleStatusChange); // Ejecutar el primer efecto

// Actualización con los accesorios de {friend: {id: 200}}
ChatAPI.unsubscribeFromFriendStatus (100, handleStatusChange); // Limpiar efecto anterior
ChatAPI.subscribeToFriendStatus (200, handleStatusChange); // Ejecutar el siguiente efecto

// Actualizar con los accesorios de {friend: {id: 300}}
ChatAPI.unsubscribeFromFriendStatus (200, handleStatusChange); // Limpiar efecto anterior
ChatAPI.subscribeToFriendStatus (300, handleStatusChange); // Ejecutar el siguiente efecto

// Desmontar
ChatAPI.unsubscribeFromFriendStatus (300, handleStatusChange); // Limpiar el último efecto
’’

Reglas de Hooks

Para trabajar con Hooks, debemos tener en cuenta que no podemos llamar a hooks dentro de funciones javaScript como, por ejemplo, manejadores de eventos usándolos dentro de Condicionales, bucles o funciones anidadas.

El equipo de React ofrece un complemento para seguir estas reglas automáticamente, [Aquí el enlace] (https://www.npmjs.com/package/eslint-plugin-react-hooks)

Escribe tu comentario
+ 2