Skip to content

Instantly share code, notes, and snippets.

Avatar

Sérgio Junior Sergioamjr

View GitHub Profile
View app.js
import { UserContextProvider } from "~hooks/useUserContext";
import UserInfo from "./UserInfo";
export default function App() {
return (
<UserContextProvider value="John">
<UserInfo />
</UserContextProvider>
);
View useUserContext.js
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>;
}
View UserInfo.js
import useUserContext from "~hooks/useUserContext";
export default function UserInfo() {
const userName = useUserContext(); // Inicialmente será '' e logo em seguida 'John'.
return <p>Olá, {userName}</p>;
}
View comparison.js
1 === 1; // true;
"batman" === "batman"; // true;
false === false; // true;
{} === {}; // false;
[] === []; // false;
() => {} === () => {}; //false;
View useImperativeHandle.js
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,
}));
View useDebugValue.js
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");
View useLayoutEffect.js
import { useState, useLayoutEffect } from "react";
function Component() {
const [isDOMLoaded, setIsDOMLoaded] = useState(false);
useLayoutEffect(() => {
setIsDOMLoaded(true);
window.localstorage.getItem("...");
}, []);
View memo.js
import { memo, useCallback } from "react";
function ListItem({ item, onSelect }) {
return (
<li>
<button onClick={() => onSelect(item)}>Select {item}</button>
</li>
);
}
View useCallback.js
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.
View useMemo.js
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]);
}