Created
June 25, 2022 18:25
-
-
Save rafinhaa/726b4711bfbc7cf76f78592830398251 to your computer and use it in GitHub Desktop.
UseMemoExample
This file contains hidden or 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
// demo https://codesandbox.io/s/divine-sunset-tppu7o | |
import axios from "axios"; | |
import { useCallback, useEffect, useState, useMemo } from "react"; | |
import "./styles.css"; | |
/** | |
* useCallback(fn,[deps]) | memoriza a função | |
* useMemo(() => fn, [deps]) | executa a função e memoriza o retorno | |
*/ | |
interface IUser { | |
id: number; | |
name: string; | |
} | |
const filter = (users: IUser[], query: string) => { | |
console.log("---- Filter ----"); | |
return users.filter((user) => user.name.toLocaleLowerCase().includes(query)); | |
}; | |
/** | |
* Toda vez que é forçado a renderização a função filter é chamada | |
* o useMemo executa a função e memoriza o retorno | |
* e só executa novamente quando as dependências mudarem | |
*/ | |
const UserList = ({ users, query }: { users: IUser[]; query: string }) => { | |
const filtered = useMemo(() => filter(users, query), [users, query]); | |
return ( | |
<> | |
{filtered.map((user) => ( | |
<div key={user.id}>{user.name}</div> | |
))} | |
</> | |
); | |
}; | |
export default function UseMemoExample() { | |
const [count, setCount] = useState(0); | |
const [users, setUsers] = useState<IUser[]>([]); | |
const [query, setQuery] = useState(""); | |
/** | |
* Toda vez que é executado o setUsers, é feito um rerender | |
* e recria a função abaixo (getUsers) | |
* como a função é dependência do useEffect | |
* ela é executada novamente entrando um loop infinito | |
* o useCallback previne esse comportamento | |
*/ | |
const getUsers = useCallback(async () => { | |
const { data } = await axios.get( | |
"https://jsonplaceholder.typicode.com/users" | |
); | |
setUsers(data); | |
}, []); | |
useEffect(() => { | |
getUsers(); | |
}, [getUsers]); | |
return ( | |
<div className="App"> | |
<h1>Hello CodeSandbox</h1> | |
<h2>{count}</h2> | |
<button onClick={() => setCount((oldState) => oldState + 1)}> | |
Forçar rerender | |
</button> | |
<br /> | |
<input type="text" onChange={(e) => setQuery(e.target.value)} /> | |
<UserList users={users} query={query} /> | |
</div> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment