Skip to content

Instantly share code, notes, and snippets.

@anderjs
Created October 14, 2020 01:32
Show Gist options
  • Select an option

  • Save anderjs/1e268d08893d735490221817c158674a to your computer and use it in GitHub Desktop.

Select an option

Save anderjs/1e268d08893d735490221817c158674a to your computer and use it in GitHub Desktop.
import React, { useEffect, useCallback, useMemo } from 'react'
function Devices () {
const [devices, setDevices] = useState()
const [products, setProducts] = useState([])
const [page, setPage] = useState(1)
// Esto se ejecutara una sola vez
useEffect(() => {
fetch('...')
.then(devices => setDevices(devices)
.catch(doSomethingWithError)
}, [])
// Esto es basicamente un componentDidUpdate, se renderizara la primera vez, y tambien las veces que cambie el state de page
useEffect(() => {
fetch(`...page?=${page}`)
.then(products => setProducts(products)
.catch(doSomethingWithError)
}, [page])
// Esta funcion no se va a volver a crear debido que no referenciamos props, ni state dentro del componente
const showDeviceLabel = useCallback(({ label })) => window.alert(label), [])
return (
<div>
{devices.map(device => <li key={device.id} onClick={() => showDeviceLabel(device)}>{device.name}</li>)}
</div>
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment