Skip to content

Instantly share code, notes, and snippets.

@luizomf
Created February 16, 2021 15:00
Show Gist options
  • Save luizomf/4d7af27ae25a85f38a131cbd8890bf3f to your computer and use it in GitHub Desktop.
Save luizomf/4d7af27ae25a85f38a131cbd8890bf3f to your computer and use it in GitHub Desktop.
React Hook useRef - Curso React
import P from 'prop-types';
import { useEffect, useMemo, useState, useRef } from 'react';
import './App.css';
const Post = ({ post, handleClick }) => {
console.log('Filho renderizou');
return (
<div key={post.id} className="post">
<h1 style={{ fontSize: '14px' }} onClick={() => handleClick(post.title)}>
{post.title}
</h1>
<p>{post.body}</p>
</div>
);
};
Post.propTypes = {
post: P.shape({
id: P.number,
title: P.string,
body: P.string,
}),
handleClick: P.func,
};
function App() {
const [posts, setPosts] = useState([]);
const [value, setValue] = useState('');
const input = useRef(null);
const contador = useRef(0);
console.log('Pai renderizou!');
// Component did mount
useEffect(() => {
fetch('https://jsonplaceholder.typicode.com/posts')
.then((r) => r.json())
.then((r) => setPosts(r));
}, []);
useEffect(() => {
input.current.focus();
console.log(input.current);
}, [value]);
useEffect(() => {
contador.current++;
});
const handleClick = (value) => {
setValue(value);
};
return (
<div className="App">
<h6>Renderizou: {contador.current}x</h6>
<p>
<input
ref={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} handleClick={handleClick} />;
})
);
}, [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