Last active
January 26, 2022 02:21
-
-
Save Ifmr24/3761a1510513d48c1b9613a6aacd4fc4 to your computer and use it in GitHub Desktop.
NextJS - React Hooks, useState, useEffect
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useState, useEffect } from 'react'; | |
export default () => { | |
// Definimos los estados | |
const [name, setName] = useState(String) | |
const [count, setCount] = useState(Number) | |
// Los estados definidos se pueden usar dentro de otras funciones | |
function obtenerName(){ | |
console.log(name) | |
} | |
// Funciona como un componentDidMount y componentDidUpdate al mismo tiempo. | |
// Es decir, se ejecutara inmediatamente cargado el sitio sin la necesidad de un boton | |
// Y se ira actualizando al mismo tiempo que vaya cambiando su valor | |
useEffect(() => { | |
document.title = `Sus clicks ${count}` | |
console.log(`El numero es: ${count}`) | |
}) | |
return( | |
<div className="main"> | |
<p>Ingresa algo: <input type="text" onChange={e => setName(e.target.value)} /></p> | |
<p>Ingresaste: {name}</p> | |
<button onClick={obtenerName}>Obtener Nombre en consola</button> | |
<br/> | |
<button onClick={() => setCount(count + 1) }>Click Me</button> | |
<br/> | |
Sus clicks {count} | |
</div> | |
) | |
} |
Es buena practica usar useState y useEffect en los componentes que estan dentro del directorio "/pages/" ?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Cool