Created
February 16, 2021 01:11
-
-
Save luizomf/95e5173e59b64c811162e52750c5cf02 to your computer and use it in GitHub Desktop.
React Hook useMemo - Curso React
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 P from 'prop-types'; | |
import { useEffect, useMemo, useState } from 'react'; | |
import './App.css'; | |
const Post = ({ post }) => { | |
console.log('Filho renderizou'); | |
return ( | |
<div key={post.id} className="post"> | |
<h1>{post.title}</h1> | |
<p>{post.body}</p> | |
</div> | |
); | |
}; | |
Post.propTypes = { | |
post: P.shape({ | |
id: P.number, | |
title: P.string, | |
body: P.string, | |
}), | |
}; | |
function App() { | |
const [posts, setPosts] = useState([]); | |
const [value, setValue] = useState(''); | |
console.log('Pai renderizou!'); | |
// Component did mount | |
useEffect(() => { | |
setTimeout(function () { | |
fetch('https://jsonplaceholder.typicode.com/posts') | |
.then((r) => r.json()) | |
.then((r) => setPosts(r)); | |
}, 5000); | |
}, []); | |
return ( | |
<div className="App"> | |
<p> | |
<input | |
type="search" | |
value={value} | |
onChange={(e) => setValue(e.target.value)} | |
/> | |
</p> | |
{useMemo(() => { | |
return ( | |
posts.length > 0 && | |
posts.map((post) => { | |
return <Post key={post.id} post={post} />; | |
}) | |
); | |
}, [posts])} | |
{posts.length <= 0 && <p>Ainda não existem posts.</p>} | |
</div> | |
); | |
} | |
export default App; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment