Skip to content

Instantly share code, notes, and snippets.

View Sergioamjr's full-sized avatar

Sérgio Junior Sergioamjr

View GitHub Profile
import { UserContextProvider } from "~hooks/useUserContext";
import UserInfo from "./UserInfo";
export default function App() {
return (
<UserContextProvider value="John">
<UserInfo />
</UserContextProvider>
);
import { useContext, createContext } from "react";
// Nosso contexto
const UserContext = createContext({ name: "" });
// Componente que recebe e atualiza o valor de name
export function UserContextProvider({ name, children }) {
return <UserContext.Provider value={name}>{children}</UserContext.Provider>;
}
import useUserContext from "~hooks/useUserContext";
export default function UserInfo() {
const userName = useUserContext(); // Inicialmente será '' e logo em seguida 'John'.
return <p>Olá, {userName}</p>;
}
1 === 1; // true;
"batman" === "batman"; // true;
false === false; // true;
{} === {}; // false;
[] === []; // false;
() => {} === () => {}; //false;
import { useImperativeHandle, forwardRef, useEffect, useRef } from "react";
const Input = forwardRef((props, parentRef) => {
const childRef = useRef();
const someMethod = () => 1;
useImperativeHandle(parentRef, () => ({
focusOnChildInput: () => childRef.current.focus(),
callChildMethod: someMethod,
}));
import { useDebugValue, useState } from "react";
function useUserStatus() {
const [isLogged, setIsLogged] = useState(false);
// ...
// Mostra um `label` no DevTools ao lado desse hook
useDebugValue(isLogged ? "Logged" : "Not logged");
import { useState, useLayoutEffect } from "react";
function Component() {
const [isDOMLoaded, setIsDOMLoaded] = useState(false);
useLayoutEffect(() => {
setIsDOMLoaded(true);
window.localstorage.getItem("...");
}, []);
import { memo, useCallback } from "react";
function ListItem({ item, onSelect }) {
return (
<li>
<button onClick={() => onSelect(item)}>Select {item}</button>
</li>
);
}
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]);
}