Skip to content

Instantly share code, notes, and snippets.

View Sergioamjr's full-sized avatar

Sérgio Junior Sergioamjr

View GitHub Profile
import { useCallback } from "react";
export default function Parent() {
const doSomething = useCallback(() => {
// A função sempre terá a mesma referência.
}, []);
const doAnotherThingWithAandB = useCallback(() => {
// Sua referência irá mudar quando a e b mudarem.
import { useMemo } from "react";
export default function Component() {
const value = useMemo(() => {
// Faz algo complexo e demorado.
// Se x e y já tiverem sido usados, irá retornar o valor anterior memorizado.
}, [x, y]);
}
function reducer(state, action) {
switch (action.type) {
case "increment":
return state + 1;
case "decrement":
return state - 1;
default:
return state;
}
}
import { useRef, useEffect, forwardRef } from "react";
export default function Parent() {
const childRef = useRef(null);
return <Text ref={childRef} />;
}
const Text = forwardRef((props, ref) => {
return <p ref={ref}>Exemplo de texto</p>;
import { useRef, useEffect, useRef, useState } from "react";
export default function Form() {
const [text, setText] = useState("");
const timeToCallSomething = useRef(null);
const fetchSomething = () => {
// Realiza alguma requisição http.
};
const time = useRef(0);
console.log(time.current); // 0;
useEffect(() => {
// Executa a função logo antes de desmontar o componente.
return () => doSomething();
}, []);
useEffect(() => {
// Faz algo com x atualizado.
}, [x]);
useEffect(fn, []);
import { useEffect } from "react";
export default function Component() {
const [filters, setFilters] = useState([]);
const fetchSomething = (params) => {};
const onResizeScreenHandler = () => {};
// Observa mudanças no estate filters.
useEffect(() => {