{"id":13622772,"url":"https://github.com/typescript-cheatsheets/react-pt","last_synced_at":"2025-04-27T08:32:09.127Z","repository":{"id":43659195,"uuid":"310669567","full_name":"typescript-cheatsheets/react-pt","owner":"typescript-cheatsheets","description":"React Typescript Cheatsheet in Portuguese 🇧🇷","archived":false,"fork":false,"pushed_at":"2023-06-22T14:44:22.000Z","size":115,"stargazers_count":57,"open_issues_count":6,"forks_count":10,"subscribers_count":5,"default_branch":"main","last_synced_at":"2025-04-20T22:25:48.299Z","etag":null,"topics":["cheatsheet","react","react-typescript","ts","typescript","typescript-playground"],"latest_commit_sha":null,"homepage":"","language":null,"has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/typescript-cheatsheets.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null}},"created_at":"2020-11-06T17:59:03.000Z","updated_at":"2024-10-01T08:23:21.000Z","dependencies_parsed_at":"2023-09-24T09:00:47.503Z","dependency_job_id":"f7820b02-33af-4449-8012-b3902bbc4d23","html_url":"https://github.com/typescript-cheatsheets/react-pt","commit_stats":{"total_commits":22,"total_committers":5,"mean_commits":4.4,"dds":0.5,"last_synced_commit":"468e615ccc8064139ef17c712f906ef03becbabd"},"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/typescript-cheatsheets%2Freact-pt","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/typescript-cheatsheets%2Freact-pt/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/typescript-cheatsheets%2Freact-pt/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/typescript-cheatsheets%2Freact-pt/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/typescript-cheatsheets","download_url":"https://codeload.github.com/typescript-cheatsheets/react-pt/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":250780042,"owners_count":21485996,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["cheatsheet","react","react-typescript","ts","typescript","typescript-playground"],"created_at":"2024-08-01T21:01:23.884Z","updated_at":"2025-04-27T08:32:06.506Z","avatar_url":"https://github.com/typescript-cheatsheets.png","language":null,"funding_links":[],"categories":["Others"],"sub_categories":[],"readme":"\u003cdiv align=\"center\"\u003e\n\u003ch1\u003eReact+TypeScript Cheatsheets em Português\u003c/h1\u003e\n\n\u003ca href=\"https://github.com/typescript-cheatsheets/react-typescript-cheatsheet/issues/81\"\u003e\n  \u003cimg\n    height=\"80\"\n    width=\"80\"\n    alt=\"react + ts logo\"\n    src=\"https://user-images.githubusercontent.com/6764957/53868378-2b51fc80-3fb3-11e9-9cee-0277efe8a927.png\"\n    align=\"left\"\n  /\u003e\n\u003c/a\u003e\n\n\u003cp\u003eCheatsheets para desenvolvedores com experiência em React que estão iniciando com TypeScript\u003c/p\u003e\n\n[**Web docs**](https://react-typescript-cheatsheet.netlify.app/docs/basic/setup) |\n[中文翻译](https://github.com/fi3ework/blog/tree/master/react-typescript-cheatsheet-cn) |\n[**Español**](https://github.com/typescript-cheatsheets/react-typescript-cheatsheet-es) |\n[Contribute!](https://github.com/typescript-cheatsheets/react-typescript-cheatsheet/blob/master/CONTRIBUTING.md) |\n[Ask!](https://github.com/typescript-cheatsheets/react-typescript-cheatsheet/issues/new/choose)\n\n\u003c/div\u003e\n\n---\n\n\u003cdiv align=\"center\"\u003e\n\n:wave: Este repositório é mantido por [@giseladifini](https://twitter.com/GiselaDifini) e [@swyx](https://twitter.com/swyx). Estamos muito felizes que você quer experimentar React com Typescript!\nSe você perceber algo de errado ou faltando, por favor abra uma [issue](https://github.com/typescript-cheatsheets/react-pt/issues/new)! :+1:\n\n\u003c/div\u003e\n\n---\n\n## Todas as dicas de React + TypeScript\n\n- **Cheatsheet Básico** ([`/README.md`](/README.md#basic-cheatsheet-table-of-contents)) é focado em ajudar desenvolvedores React a começar a usar TS com React **apps**\n  - Foco nas melhores práticas com exemplos para copiar e colar.\n  - Explica alguns tipos básicos de uso de TS e configuração ao longo do caminho.\n  - Responde às perguntas mais frequentes.\n  - Não cobre a lógica de tipo genérico em detalhes. Em vez disso, preferimos ensinar técnicas de solução de problemas simples para iniciantes.\n  - O objetivo é se familiarizar com TS sem precisar aprender _muito_ sobre TS.\n- **Cheatsheet Avançado** ([`/AVANÇADO.md`](https://react-typescript-cheatsheet.netlify.app/docs/advanced)) ajuda a mostrar e explicar o uso avançado de tipos genéricos para pessoas que escrevem utilitários/funções/props de renderização/componentes de ordem superior (HOCs) reutilizáveis ​​e **bibliotecas** TS+React.\n  - Possui dicas e truques diversos para usuários profissionais.\n  - Conselhos para contribuir com DefinitelyTyped.\n  - O Objetivo é tirar _total vantagem_ sobre o TypeScript.\n- **Cheatsheet de migração** ([`/MIGRANDO.md`](https://react-typescript-cheatsheet.netlify.app/docs/migration)) ajuda a reunir conselhos para a migração incremental de grandes bases de código de JS ou Flow, **de pessoas que já fizeram isso**.\n  - Nós não tentamos convencer as pessoas a mudar, apenas ajudar as pessoas que já decidiram isso.\n  - ⚠️ Esta é uma nova cheatsheet, toda ajuda é bem-vinda.\n- **Cheatsheet de HOCs** ([`/HOC.md`](https://react-typescript-cheatsheet.netlify.app/docs/hoc)) especificamente ensina as pessoas a escrever HOCs com a ajuda de exemplos.\n  - Familiaridade com [Genéricos](https://www.typescriptlang.org/docs/handbook/generics.html) é necessário.\n  - ⚠️ Esta é uma nova cheatsheet, toda a assistência é bem-vinda.\n\n---\n\n### Tabela de conteúdos da Cheatsheet básica\n\n\u003cdetails\u003e\n\n\u003csummary\u003e\u003cb\u003eExpandir Tabela de Conteúdo\u003c/b\u003e\u003c/summary\u003e\n\n\u003c!--START-SECTION:setup-toc--\u003e\n\n- [Seção 1: Configuração](#seção-1-configuração)\n- [Pré-requisitos](#pré-requisitos)\n- [Ferramentas iniciais de React + TypeScript](#ferramentas-iniciais-de-react--typeScript)\n- [Importar React](#importar-react)\n\u003c!--END-SECTION:setup-toc--\u003e\n- [Seção 2: Primeiros Passos](#seção-2-primeiros-passos)\n  - [Componente de Função](#componente-de-função)\n  - [Hooks](#hooks)\n  - [useState](#usestate)\n  - [useReducer](#usereducer)\n  - [useEffect](#useeffect)\n  - [useRef](#useref)\n  - [useImperativeHandle](#useimperativehandle)\n  - [Hooks Customizados](#custom-hooks)\n  - [Componentes de Classe](#class-components)\n  - [Talvez você não precise do `defaultProps`](#you-may-not-need-defaultprops)\n  - [\"Tipando\" `defaultProps`](#typing-defaultprops)\n  - [Consumindo Props de um Componente com defaultProps](#consuming-props-of-a-component-with-defaultprops)\n    - [Declaração do Problema](#problem-statement)\n    - [Solução](#solution)\n  - [Discussões e Conhecimentos Diversos](#misc-discussions-and-knowledge)\n  - [Tipos ou Interfaces?](#types-or-interfaces)\n  - [Exemplos básicos do tipo Prop](#basic-prop-types-examples)\n  - [Exemplos úteis do tipo React Prop](#useful-react-prop-type-examples)\n  - [getDerivedStateFromProps](#getDerivedStateFromProps)\n  - [Formulários e Eventos](#forms-and-events)\n  - [Context](#context)\n  - [Exemplo Básico](#basic-example)\n  - [Exemplo Extendido](#extended-example)\n  - [forwardRef/createRef](#forwardrefcreateref)\n  - [Portais](#portals)\n  - [Limites de erros](#error-boundaries)\n    - [Opção 1: Usando react-error-boundary](#option-1-using-react-error-boundary)\n    - [Opção 2: Criando um componente \"error boundary\" personalizado](#options-2-writing-your-custom-error-boundary-component)\n  - [Concurrent React/React Suspense](#concurrent-reactreact-suspense)\n  \u003c!--START-SECTION:types-toc--\u003e\n- [Manual de resolução de problemas: Tipos](#troubleshooting-handbook-types)\n  - [Tipos de União e Tipos de Proteção](#union-types-and-type-guarding)\n  - [Tipos Opcionais](#optional-types)\n  - [Tipos de Enum](#enum-types)\n  - [Tipos de Asserção](#type-assertion)\n  - [Simulando Tipos Nominais](#simulating-nominal-types)\n  - [Tipos de Interseção](#intersection-types)\n  - [Tipos de União](#union-types)\n  - [Sobrecarregando Tipos de Função](#overloading-function-types)\n  - [Usando Tipos Inferidos](#using-inferred-types)\n  - [Usando Tipos Parciais](#using-partial-types)\n  - [Os Tipos de que preciso não foram exportados!](#the-types-i-need-werent-exported)\n  - [Os Tipos de que preciso não existem!](#the-types-i-need-dont-exist)\n    - [Exagerando com `any` em tudo](#slapping-any-on-everything)\n    - [Autogerando tipos](#autogenerate-types)\n    - [Tipando Hooks Exportados](#typing-exported-hooks)\n    - [Tipando Componentes Exportados](#typing-exported-components)\n    \u003c!--END-SECTION:types-toc--\u003e\n- [Manual de resolução de problemas: Operadores](#troubleshooting-handbook-operators)\n- [Manual de resolução de problemas: Utilitários](#troubleshooting-handbook-utilities)\n- [Manual de resolução de problemas: tsconfig.json](#troubleshooting-handbook-tsconfigjson)\n- [Manual de resolução de problemas: Erros en tipos oficiais](#troubleshooting-handbook-bugs-in-official-typings)\n- [Bases de código de React + TypeScript recomendadas para aprender](#recommended-react--typescript-codebases-to-learn-from)\n- [Ferramentas e integração em editores](#editor-tooling-and-integration)\n- [Linting](#linting)\n- [Outros recursos sobre React + TypeScript](#other-react--typescript-resources)\n- [Discussões recomendadas sobre React + TypeScript](#recommended-react--typescript-talks)\n- [Hora de realmente aprender TypeScript](#time-to-really-learn-typescript)\n- [Aplicação de Exemplo](#example-app)\n- [Minha pergunta não foi respondida aqui!](#my-question-isnt-answered-here)\n  - [Contribuidores](#contributors)\n\n\u003c/details\u003e\n\n\u003c!--START-SECTION:setup--\u003e\n\n# Seção 1: Configuração\n\n## Pré-requisitos\n\n1. Uma boa compreensão de [React](https://reactjs.org).\n2. Familiaridade com os tipos básicos de [TypeScript](https://www.typescriptlang.org/docs/handbook/basic-types.html) ( [O guia de 2ality](http://2ality.com/2018/04/type-notation-typescript.html) é de grande ajuda. Se você é completamente novato em TypeScript, dê uma olhada no [tutorial de chibicode](https://ts.chibicode.com/todo/) ).\n3. Ter lido [a seção de TypeScript na documentação oficial do React](https://reactjs.org/docs/static-type-checking.html#typescript).\n4. Ter lido [a seção do React do novo playground de TypeScript](http://www.typescriptlang.org/play/index.html?jsx=2\u0026esModuleInterop=true\u0026e=181#example/typescript-with-react) ( Opcional: também acompanhar os mais de 40 exemplos na seção de exemplos do [playground](http://www.typescriptlang.org/play/index.html) ).\n\nEste guia sempre assumirá que você está usando a última versão de Typescript. Notas para versões mais antigas usarão a etiqueta `\u003cdetails\u003e`.\n\n## Ferramentas iniciais de React + TypeScript\n\nConfigurações na nuvem:\n\n- [Playground do TypeScript com React](https://www.typescriptlang.org/play?#code/JYWwDg9gTgLgBAKjgQwM5wEoFNkGN4BmUEIcA5FDvmQNwCwAUKJLHAN5wCuqWAyjMhhYANFx4BRAgSz44AXzhES5Snhi1GjLAA8W8XBAB2qeAGEInQ0KjjtycABsscALxwAFAEpXAPnaM4OANjeABtA0sYUR4Yc0iAXVcxPgEhdwAGT3oGAOTJaXx3L19-BkDAgBMIXE4QLCsAOhhgGCckgAMATQsgh2BcAGssCrgAEjYIqwVmutR27MC5LM0yuEoYTihDD1zAgB4K4AA3H13yvbAfbs5e-qGRiYspuBmsVD2Aekuz-YAjThgMCMcCMpj6gxcbGKLj8MTiVnck3gAGo4ABGTxyU6rcrlMF3OB1H5wT7-QFGbG4z6HE65ZYMOSMIA) apenas se você estiver depurando tipos (e relatando problemas), não para executar código.\n- [CodeSandbox](http://ts.react.new) - IDE na nuvem, inicializa super rápido.\n- [Stackblitz](https://stackblitz.com/edit/react-typescript-base) - IDE na nuvem, inicializa super rápido.\n\nConfigurações de desenvolvimento local:\n\n- [Next.js](https://nextjs.org/docs/basic-features/typescript): `npx create-next-app -e with-typescript` irá criar no seu diretório atual.\n- [Create React App](https://facebook.github.io/create-react-app/docs/adding-typescript): `npx create-react-app name-of-app --template typescript` irá criar em um novo diretório.\n- [Meteor](https://guide.meteor.com/build-tool.html#typescript): `meteor create --typescript name-of-my-new-typescript-app`\n- [Ignite](https://github.com/infinitered/ignite#use-ignite-andross-infinite-red-andross-boilerplate) para React Native: `ignite new myapp`\n- [TSDX](https://tsdx.io/): `npx tsdx create mylib` para Creating React+TS _libraries_\n\n\u003cdetails\u003e\n\u003csummary\u003e\nOutras ferramentas\n\u003c/summary\u003e\n\nFerramentas menos maduras mas que vale a pena conferir:\n\n- [Vite](https://twitter.com/swyx/status/1282727239230996480?lang=en): `npm init vite-app my-react-project --template react-ts` (nota - ainda não está na versão v1.0, mas é muito rápida).\n- [Snowpack](\u003chttps://www.snowpack.dev/#create-snowpack-app-(csa)\u003e): `npx create-snowpack-app my-app --template app-template-react-typescript`\n- [Docusaurus v2](https://v2.docusaurus.io/docs/installation) com [suporte a TypeScript](https://v2.docusaurus.io/docs/typescript-support)\n- [Parcel](https://v2.parceljs.org/languages/typescript/)\n- [JP Morgan's `modular`](https://github.com/jpmorganchase/modular): CRA + TS + Yarn Workspaces toolkit. `yarn create modular-react-app \u003cproject-name\u003e`\n\nManual de configuração:\n\n- [O guia de Basarat](https://github.com/basarat/typescript-react/tree/master/01%20bootstrap) para uma **configuração manual** de React + TypeScript + Webpack + Babel.\n- Em particular, certifique-se de ter instalado `@types/react` e `@types/react-dom` .( [Leia mais sobre o projeto DefinitelyTyped caso você não esteja familiarizado](https://definitelytyped.org/) ).\n- Existem também muitos _boilerplates_ de React + Typescript. Por favor consulte [nossa lista de outros recursos](https://react-typescript-cheatsheet.netlify.app/docs/basic/recommended/resources/).\n\n\u003c/details\u003e\n\n## Import React\n\n```tsx\nimport * as React from 'react';\nimport * as ReactDOM from 'react-dom';\n```\n\nEste é o [caminho mais seguro no futuro](https://www.reddit.com/r/reactjs/comments/iyehol/import_react_from_react_will_go_away_in_distant/) para importar React. Se você definir `--allowSyntheticDefaultImports` (ou adicionar` \"allowSyntheticDefaultImports\": true`) em seu `tsconfig.json`, você poderá importar como se faz normalmente em jsx:\n\n```tsx\nimport React from 'react';\nimport ReactDOM from 'react-dom';\n```\n\n\u003cdetails\u003e\n\n\u003csummary\u003eExplicação\u003c/summary\u003e\n\nPor que usar `allowSyntheticDefaultImports` ao invés de `esModuleInterop`? [Daniel Rosenwasser](https://twitter.com/drosenwasser/status/1003097042653073408) comentou que é melhor para webpack/parcel. Para consultar mais argumentos dessa discussão \u003chttps://github.com/wmonk/create-react-app-typescript/issues/214\u003e\n\nVocê também deveria verificar [a nova documentação do TypeScript para descrições oficiais entre cada _flag_ do compilador](https://www.typescriptlang.org/tsconfig#allowSyntheticDefaultImports)!\n\n\u003c/details\u003e\n\n\u003c!--END-SECTION:setup--\u003e\n\n\u003c!--START-SECTION:function-components--\u003e\n\n# Seção 2: Primeiros Passos\n\n## Componente de Função\n\nPodem ser escritos como funções normais que recebem `props` como argumento e retornam um elemento JSX.\n\n```tsx\ntype AppProps = { message: string }; /* também se pode usar uma interface */\nconst App = ({ message }: AppProps) =\u003e \u003cdiv\u003e{message}\u003c/div\u003e;\n```\n\n\u003cdetails\u003e\n\n\u003csummary\u003e\u003cb\u003ePor que `React.FC` é desencorajado? E sobre `React.FunctionComponent` / `React.VoidFunctionComponent`?\u003c/b\u003e\u003c/summary\u003e\n\nVocê pode ver isso em muitas bases de código React + TypeScript:\n\n```tsx\nconst App: React.FunctionComponent\u003c{ message: string }\u003e = ({ message }) =\u003e (\n  \u003cdiv\u003e{message}\u003c/div\u003e\n);\n```\n\nNo entanto, o consenso geral hoje é que o uso de `React.FunctionComponent` (ou a abreviação` React.FC`) é [desencorajado] (https://github.com/facebook/create-react-app/pull/8177). Isto é um ponto de vista, é claro, mas se você concorda e deseja remover `React.FC` da sua base de código, você pode usar [este jscodeshift codemod] (https://github.com/gndelia/codemod-replace-react- fc-typescript).\n\nAlgumas diferenças da versão de \"função normal\":\n\n- `React.FunctionComponent` é explícito sobre o tipo de retorno, enquanto a versão normal da função é implícita (ou então precisa de anotações adicionais).\n\n- Fornece verificação de tipos e preenchimento automático para propriedades estáticas como `displayName`,` propTypes` e `defaultProps`.\n\n  - Observe que existem alguns problemas conhecidos usando `defaultProps` com` React.FunctionComponent`. Consulte [este problema para obter detalhes] (https://github.com/typescript-cheatsheets/react-typescript-cheatsheet/issues/87). Nós mantemos uma seção `defaultProps` separada para que você também possa consultar.\n\n- Fornece uma definição implícita de `children` (veja abaixo) - no entanto, há alguns problemas com o tipo `children` implícito (por exemplo, DefinitelyTyped#33006), e é melhor ser explícito sobre os componentes que consomem `children`, de qualquer maneira.\n\n```tsx\nconst Title: React.FunctionComponent\u003c{ title: string }\u003e = ({\n  children,\n  title,\n}) =\u003e \u003cdiv title={title}\u003e{children}\u003c/div\u003e;\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e\nUsando `React.VoidFunctionComponent` ou` React.VFC` como alternativa\n\u003c/summary\u003e\n\nA partir da versão [@types/react 16.9.48] (https://github.com/DefinitelyTyped/DefinitelyTyped/pull/46643), você também poderá usar o tipo `React.VoidFunctionComponent` ou `React.VFC` se quiser tipar `children` explicitamente. Esta é uma solução provisória até que `FunctionComponent` não aceite nenhum `children` por padrão (planejado para `@types/react@^18.0.0`).\n\n```ts\ntype Props = { foo: string };\n\n// OK agora mas futuramente causará erro\nconst FunctionComponent: React.FunctionComponent\u003cProps\u003e = ({\n  foo,\n  children,\n}: Props) =\u003e {\n  return (\n    \u003cdiv\u003e\n      {foo} {children}\n    \u003c/div\u003e\n  ); // OK\n};\n\n// OK agora mas futuramente se tornará obsoleto\nconst VoidFunctionComponent: React.VoidFunctionComponent\u003cProps\u003e = ({\n  foo,\n  children,\n}) =\u003e {\n  return (\n    \u003cdiv\u003e\n      {foo}\n      {children}\n    \u003c/div\u003e\n  );\n};\n```\n\n\u003c/details\u003e\n- _No futuro_, ele poderá marcar automaticamente os `props` como `readonly` (somente leitura), embora isso seja um ponto discutível se o objeto `props` for desestruturado na lista de parâmetros.\n\nNa maioria dos casos, faz pouca diferença qual sintaxe é usada, mas você pode preferir a natureza mais explícita de `React.FunctionComponent`.\n\n\u003c/details\u003e\n\n\u003cdetails\u003e\n\u003csummary\u003e\u003cb\u003eProblemas menores\u003c/b\u003e\u003c/summary\u003e\n\nEsses padrões não são suportados:\n\n** Renderização condicional **\n\n```tsx\nconst MyConditionalComponent = ({ shouldRender = false }) =\u003e\n  shouldRender ? \u003cdiv /\u003e : false; // tampouco faça isso em JS\nconst el = \u003cMyConditionalComponent /\u003e; // gera um erro\n```\n\nIsso ocorre porque, devido às limitações do compilador, os componentes de função não podem retornar nada além de uma expressão JSX ou `null`, caso contrário, ele reclama com uma mensagem de erro enigmática dizendo que outro tipo não pode ser atribuído ao Elemento.\n\n```tsx\nconst MyArrayComponent = () =\u003e Array(5).fill(\u003cdiv /\u003e);\nconst el2 = \u003cMyArrayComponent /\u003e; // gera um erro\n```\n\n**Array.fill**\n\nInfelizmente, apenas anotar o tipo de função não vai ajudar, então se você realmente precisar retornar outros tipos exóticos que o React suporta, será necessário executar uma declaração de tipo:\n\n```tsx\nconst MyArrayComponent = () =\u003e (Array(5).fill(\u003cdiv /\u003e) as any) as JSX.Element;\n```\n\n[Veja o comentário de @ferdaber aqui] (https://github.com/typescript-cheatsheets/react-typescript-cheatsheet/issues/57).\n\n\u003c/details\u003e\n\n\u003c!--END-SECTION:function-components--\u003e\n\n\u003c!--START-SECTION:hooks--\u003e\n\n## Hooks\n\nHá suporte para Hooks em [`@types/react` a partir da versão v16.8](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/a05cc538a42243c632f054e42eab483ebf1560ab/types/react/index.d.ts#L800-L1031).\n\n## useState\n\nInferência automática de tipos funciona bem com valores simples\n\n```tsx\nconst [val, toggle] = React.useState(false);\n//  infere-se que `val` é do tipo boolean\n// `toggle` aceita apenas booleans\n```\n\nVeja também no artigo em inglês (utilizando [Using Inferred Types](https://react-typescript-cheatsheet.netlify.app/docs/basic/troubleshooting/types/#using-inferred-types) se precisar usar um tipo complexo para o qual você depende da inferência.\n\nNo entanto, muitos hooks são inicializados com valores nulos e você pode se perguntar como deve fazer para definir o tipo. Declare explicitamente o tipo e use um tipo de união (union type):\n\n```tsx\nconst [user, setUser] = React.useState\u003cIUser | null\u003e(null);\n\n// mais adiante...\nsetUser(newUser);\n```\n\nVocê também pode usar asserções de tipo (type assertions) se um estado for inicializado logo após o setup e sempre tiver um valor definido após o setup:\n\n```tsx\nconst [user, setUser] = React.useState\u003cIUser\u003e({} as IUser);\n\n// mais adiante...\nsetUser(newUser);\n```\n\n\"Mentimos\" temporariamente para o compilador de Typescript que `{}` é do tipo `IUser`. Você deve então configurar o estado de `user` — se não o fizer, o resto do seu código pode depender do fato de que `user` é do tipo `IUser` e isso pode levar a erros em tempo de execução (runtime errors).\n\n## useReducer\n\nVocê pode utilizar Uniões de tipos com propriedades definidas ([Discriminated Unions](https://www.typescriptlang.org/docs/handbook/typescript-in-5-minutes-func.html#discriminated-unions)) para actions da função reducer. Não esqueça de definir o tipo de retorno, caso contário, o compilador irá inferir o tipo.\n\n```tsx\nconst initialState = { count: 0 };\n\ntype ACTIONTYPE =\n  | { type: \"increment\"; payload: number }\n  | { type: \"decrement\"; payload: string };\n\nfunction reducer(state: typeof initialState, action: ACTIONTYPE) {\n  switch (action.type) {\n    case \"increment\":\n      return { count: state.count + action.payload };\n    case \"decrement\":\n      return { count: state.count - Number(action.payload) };\n    default:\n      throw new Error();\n  }\n}\n\nfunction Counter() {\n  const [state, dispatch] = React.useReducer(reducer, initialState);\n  return (\n    \u003c\u003e\n      Count: {state.count}\n      \u003cbutton onClick={() =\u003e dispatch({ type: \"decrement\", payload: \"5\" })}\u003e\n        -\n      \u003c/button\u003e\n      \u003cbutton onClick={() =\u003e dispatch({ type: \"increment\", payload: 5 })}\u003e\n        +\n      \u003c/button\u003e\n    \u003c/\u003e\n  );\n}\n```\n\n[Veja no TypeScript Playground](https://www.typescriptlang.org/play?#code/LAKFEsFsAcHsCcAuACAVMghgZ2QJQKYYDGKAZvLJMgOTyEnUDcooRsAdliuO+IuBgA2AZUQZE+ZAF5kAbzYBXdogBcyAAwBfZmBCIAntEkBBAMIAVAJIB5AHLmAmgAUAotOShkyAD5zkBozVqHiI6SHxlagAaZGgMfUFYDAATNXYFSAAjfHhNDxAvX1l-Q3wg5PxQ-HDImLiEpNTkLngeAHM8ll1SJRJwDmQ6ZIUiHIAKLnEykqNYUmQePgERMQkY4n4ONTMrO0dXAEo5T2aAdz4iAAtkMY3+9gA6APwj2ROvImxJYPYqmsRqCp3l5BvhEAp4Ow5IplGpJhIHjCUABqTB9DgPeqJFLaYGfLDfCp-CIAoEFEFeOjgyHQ2BKVTNVb4RF05TIAC0yFsGWy8Fu6MeWMaB1x5K8FVIGAUglUwK8iEuFFOyHY+GVLngFD5Bx0Xk0oH13V6myhplZEm1x3JbE4KAA2vD8DFkuAsHFEFcALruAgbB4KAkEYajPlDEY5GKLfhCURTHUnKkQqFjYEAHgAfHLkGb6WpZI6WfTDRSvKnMgpEIgBhxTIJwEQANZSWRjI5SdPIF1u8RXMayZ7lSphEnRWLxbFNagAVmomhF6fZqYA9OXKxxM2KQWWK1WoTW643m63pB2u+7e-3SkEQsPamOGik1FO55p08jl6vdxuKcvv8h4yAmhAA)\n\n\u003cdetails\u003e\n\n\u003csummary\u003e\u003cb\u003eUso do tipo `Reducer` da biblioteca `redux`\u003c/b\u003e\u003c/summary\u003e\n\nCaso você use a biblioteca [redux](https://github.com/reduxjs/redux) para escrever a reducer function, ela fornece um helper conveniente do formato `Reducer\u003cState, Action\u003e` que cuida do tipo do retorno para você.\n\nAssim, o exemplo de reducer acima se torna:\n\n```tsx\nimport { Reducer } from 'redux';\n\nexport function reducer: Reducer\u003cAppState, Action\u003e() {}\n```\n\n\u003c/details\u003e\n\n## useEffect / useLayoutEffect\n\nAmbos `useEffect` e `useLayoutEffect` são usados para executar \u003cb\u003eefeitos colaterais\u003c/b\u003e e retornam uma função de limpeza opcional, o que significa que se eles não lidam com retorno de valores, nenhum tipo é necessário. Ao usar `useEffect`, tome cuidado para não retornar nada além de uma função ou `undefined`, caso contrário, tanto o TypeScript quanto o React apresentarão error. Isso pode ser sutil ao usar arrow functions:\n\n```ts\nfunction DelayedEffect(props: { timerMs: number }) {\n  const { timerMs } = props;\n\n  useEffect(\n    () =\u003e\n      setTimeout(() =\u003e {\n        /* faça coisas aqui */\n      }, timerMs),\n    [timerMs]\n  );\n  // um exemplo ruim! setTimeout implicitamente retorna número (tipo number)\n  // porque o corpo da arrow function não está entre chaves\n  return null;\n}\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e\nSolução para o exemplo acima\n\u003c/summary\u003e\n\n```tsx\nfunction DelayedEffect(props: { timerMs: number }) {\n  const { timerMs } = props;\n\n  useEffect(() =\u003e {\n    setTimeout(() =\u003e {\n      /* faça coisas aqui */\n    }, timerMs);\n  }, [timerMs]);\n  // melhor; utilize a keyword void para ter certeza de que retornará undefined\n  return null;\n}\n```\n\n\u003c/details\u003e\n\n## useRef\n\nEm TypeScript, `useRef` retorna uma referência que pode ser [somente leitura](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/abd69803c1b710db58d511f4544ec1b70bc9077c/types/react/v16/index.d.ts#L1025-L1039) ou [mutável](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/abd69803c1b710db58d511f4544ec1b70bc9077c/types/react/v16/index.d.ts#L1012-L1023), a depender se o tipo fornecido cobre totalmente o valor inicial ou não. Escolha um que se adapte ao seu caso de uso.\n\n### Opção 1: ref de um elemento da DOM\n\n**[Para acessar um elemento da DOM](https://reactjs.org/docs/refs-and-the-dom.html):** forneça apenas o tipo de elemento como argumento e use `null` como valor inicial. Neste caso, a referência retornada terá um `.current` somente leitura que é gerenciado pelo React. O TypeScript espera que você dê esta referência à prop `ref` de um elemento:\n\n```tsx\nfunction Foo() {\n  // - Se possível, seja o mais específico possível. Por exemplo, HTMLDivElement\n  // é melhor que HTMLElement e muito melhor que Element.\n  // - Em termos técnicos, isso retorna RefObject\u003cHTMLDivElement\u003e\n  const divRef = useRef\u003cHTMLDivElement\u003e(null);\n\n  useEffect(() =\u003e {\n    // Observe que ref.current pode ser null. Isso é esperado, porque você pode\n    // renderizar condicionalmente o elemento da ref, ou você poderia esquecer de atribuí-lo a um elemento\n    if (!divRef.current) throw Error(\"divRef is not assigned\");\n\n    // Agora você tem certeza que divRef.current é um HTMLDivElement\n    doSomethingWith(divRef.current);\n  });\n\n  // Atribua a ref a um elemento para que o React possa gerenciar-lo pra você\n  return \u003cdiv ref={divRef}\u003eetc\u003c/div\u003e;\n}\n```\n\nSe você tem certeza de que `divRef.current` nunca será nulo, também é possível usar o operador de asserção não nulo `!`:\n\n```tsx\nconst divRef = useRef\u003cHTMLDivElement\u003e(null!);\n// Mais tarde... não precisa checar se o elemento é nulo\ndoSomethingWith(divRef.current);\n```\n\nObserve que você está desativando a segurança de tipo aqui - você terá um erro de tempo de execução se esquecer de atribuir a referência a um elemento na renderização ou se o elemento com ref for renderizado condicionalmente.\n\n\u003cdetails\u003e\n\u003csummary\u003e\nDica: Escolhendo qual `HTMLElement` usar\n\u003c/summary\u003e\n\nRefs demandam especificidade - não é suficiente apenas especificar qualquer `HTMLElement` antigo. Se você não souber o nome do tipo de elemento necessário, verifique [lib.dom.ts](https://github.com/microsoft/TypeScript/blob/v3.9.5/lib/lib.dom. d.ts#L19224-L19343) ou cometa um erro de tipo intencional e deixe o compilador lhe dizer o tipo correto:\n\n![image](https://user-images.githubusercontent.com/6764957/116914284-1c436380-ac7d-11eb-9150-f52c571c5f07.png)\n\n\u003c/details\u003e\n\n### Opção 2: Valor ref mutável\n\n**[Para ter um valor mutável](https://reactjs.org/docs/hooks-faq.html#is-there-something-like-instance-variables):** forneça o tipo desejado e verifique se o valor inicial pertence totalmente a esse tipo:\n\n```tsx\nfunction Foo() {\n  // Tecnicamente, isto retorna MutableRefObject\u003cnumber | null\u003e\n  const intervalRef = useRef\u003cnumber | null\u003e(null);\n\n  // Você mesmo gerência a ref (por isso se chama MutableRefObject!)\n  useEffect(() =\u003e {\n    intervalRef.current = setInterval(...);\n    return () =\u003e clearInterval(intervalRef.current);\n  }, []);\n\n  // A ref (intervalRef) não é passado para a prop \"ref\" de nenhum elemento\n  return \u003cbutton onClick={/* clearInterval the ref */}\u003eCancel timer\u003c/button\u003e;\n}\n```\n\n### Veja também (conteúdo em inglês)\n\n- [Issue relacionada por @rajivpunjabi](https://github.com/typescript-cheatsheets/react/issues/388) - [Playground](https://www.typescriptlang.org/play#code/JYWwDg9gTgLgBAKjgQwM5wEoFNkGN4BmUEIcARFDvmQNwCwAUI7hAHarwCCYYcAvHAAUASn4A+OAG9GjOHAD0CBLLnKGcxHABiwKBzgQwMYGxS4WUACbBWAczgwIcSxFwBXEFlYxkxtgDoVTQBJVmBjZAAbOAA3KLcsOAB3YEjogCNE1jc0-zgAGQBPG3tHOAAVQrAsAGVcKGAjOHTCuDdUErhWNgBabLSUVFQsWBNWA2qoX2hA9VU4AGFKXyx0AFk3H3TIxOwCOAB5dIArLHwgpHcoSm84MGJJmFbgdG74ZcsDVkjC2Y01f7yFQsdjvLAEACM-EwVBg-naWD2AB4ABLlNb5GpgZCsACiO083jEgn6kQAhMJ6HMQfpKJCFpE2IkBNg8HCEci0RisTj8VhCTBiaSKVSVIoAaoLnBQuFgFFYvFEikBpkujkMps4FgAB7VfCdLmY7F4gleOFwAByEHg7U63VYfXVg2Go1MhhG0ygf3mAHVUtF6jgYLtwUdTvguta4Bstjs9mGznCpVcbvB7u7YM90B8vj9vYgLkDqWxaeCAEzQ1n4eHDTnoo2801EknqykyObii5SmpnNifA5GMZmCzWOwOJwudwC3xjKUyiLROKRBLJf3NLJO9KanV64xj0koVifQ08k38s1Sv0DJZBxIx5DbRGhk6J5Nua5mu4PEZPOAvSNgsgnxsHmXZzIgRZyDSYIEAAzJWsI1k+BCovWp58gKcAAD5qmkQqtqKHbyCexoYRecw7IQugcAs76ptCdIQv4KZmoRcjyMRaGkU28A4aSKiUXAwwgpYtEfrcAh0mWzF0ax7bsZx3Lceetx8eqAlYPAMAABa6KJskSXAdKwTJ4kwGxCjyKy-bfK05SrDA8mWVagHAbZeScOY0CjqUE6uOgqDaRAOSfKqOYgb8KiMaZ9GSeCEIMkyMVyUwRHWYc7nSvAgUQEk6AjMQXpReWyWGdFLHeBZHEuTCQEZT8xVwaV8BxZCzUWZQMDvuMghBHASJVnCWhTLYApiH1chIqgxpGeCfCSIxAC+Yj3o+8YvvgSLyNNOLjeBGhTTNdLzVJy3reGMBbTtrB7RoB3XbNBAneCsHLatcbPhdV3GrdB1WYhw3IKNZq-W2DCLYRO7QPAljgsgORcDwVJAA)\n- [Exemplo de Stefan Baumgartner](https://fettblog.eu/typescript-react/hooks/#useref) - [Playground](https://www.typescriptlang.org/play/?jsx=2#code/JYWwDg9gTgLgBAJQKYEMDG8BmUIjgIilQ3wFgAoCzAVwDsNgJa4AVJADxgElaxqYA6sBgALAGIQ01AM4AhfjCYAKAJRwA3hThwA9DrjBaw4CgA2waUjgB3YSLi1qp0wBo4AI35wYSZ6wCeYEgAymhQwGDw1lYoRHCmEBAA1oYA5nCY0HAozAASLACyADI8fDAAoqZIIEi0MFpwaEzS8IZllXAAvIjEMAB0MkjImAA8+cWl-JXVtTAAfEqOzioA3A1NtC1wTPIwirQAwuZoSV1wql1zGg3aenAt4RgOTqaNIkgn0g5ISAAmcDJvBA3h9TsBMAZeFNXjl-lIoEQ6nAOBZ+jddPpPPAmGgrPDEfAUS1pG5hAYvhAITBAlZxiUoRUqjU6m5RIDhOi7iIUF9RFYaqIIP9MlJpABCOCAUHJ0eDzm1oXAAGSKyHtUx9fGzNSacjaPWq6Ea6gI2Z9EUyVRrXV6gC+DRtVu0RBgxuYSnRIzm6O06h0ACpIdlfr9jExSQyOkxTP5GjkPFZBv9bKIDYSmbNpH04ABNFD+CV+nR2636kby+BETCddTlyo27w0zr4HycfC6L0lvUjLH7baHY5Jas7BRMI7AE42uYSUXed6pkY6HtMDulnQruCrCg2oA)\n\n## useImperativeHandle\n\n_Não temos muito ainda sobre esse tema, [há uma discussão nas issues do repositório original](https://github.com/typescript-cheatsheets/react/issues/106). Por favor, contribua se puder!_\n\n```tsx\ntype ListProps\u003cItemType\u003e = {\n  items: ItemType[];\n  innerRef?: React.Ref\u003c{ scrollToItem(item: ItemType): void }\u003e;\n};\n\nfunction List\u003cItemType\u003e(props: ListProps\u003cItemType\u003e) {\n  useImperativeHandle(props.innerRef, () =\u003e ({\n    scrollToItem() {},\n  }));\n  return null;\n}\n```\n\n## Custom Hooks\n\nSe você estiver retornando um array em seu Custom Hook (hooks customizados), você vai querer evitar a inferência de tipo, pois o TypeScript irá inferir um tipo de união (quando, na verdade, você quer tipos diferentes em cada posição do array). Em vez disso, use [const assertions do TypeScript 3.4](https://devblogs.microsoft.com/typescript/announcing-typescript-3-4/#const-assertions):\n\n```tsx\nexport function useLoading() {\n  const [isLoading, setState] = React.useState(false);\n  const load = (aPromise: Promise\u003cany\u003e) =\u003e {\n    setState(true);\n    return aPromise.finally(() =\u003e setState(false));\n  };\n  return [isLoading, load] as const; // infere [boolean, typeof load] ao invés de (boolean | typeof load)[]\n}\n```\n\n[Veja no TypeScript Playground](https://www.typescriptlang.org/play/?target=5\u0026jsx=2#code/JYWwDg9gTgLgBAJQKYEMDG8BmUIjgcilQ3wFgAoCpAD0ljkwFcA7DYCZuRgZyQBkIKACbBmAcwAUASjgBvCnDhoO3eAG1g3AcNFiANHF4wAyjBQwkAXTgBeRMRgA6HklPmkEzCgA2vKQG4FJRV4b0EhWzgJFAAFHBBNJAAuODjcRIAeFGYATwA+GRs8uSDFIzcLCRgoRiQA0rgiGEYoTlj4xMdMUR9vHIlpW2Lys0qvXzr68kUAX0DpxqRm1rgNLXDdAzDhaxRuYOZVfzgAehO4UUwkKH21ACMICG9UZgMYHLAkCEw4baFrUSqVARb5RB5PF5wAA+cHen1BfykaksFBmQA)\n\nDessa forma, quando você desestrutura (desctructure), você obtém os tipos certos com base na posição de desestruturação.\n\n\u003cdetalhes\u003e\n\u003csummary\u003e\u003cb\u003eAlternativa: definir um tipo de retorno de tupla (tuple)\u003c/b\u003e\u003c/summary\u003e\n\nSe você está [tendo problemas com const assertions](https://github.com/babel/babel/issues/9800), você também pode declarar ou definir os tipos do retorno da função:\n\n```tsx\nexport function useLoading() {\n  const [isLoading, setState] = React.useState(false);\n  const load = (aPromise: Promise\u003cany\u003e) =\u003e {\n    setState(true);\n    return aPromise.finally(() =\u003e setState(false));\n  };\n  return [isLoading, load] as [\n    boolean,\n    (aPromise: Promise\u003cany\u003e) =\u003e Promise\u003cany\u003e\n  ];\n}\n```\n\nUma função auxiliar que define o tipe de tuplas automaticamente também pode ser útil se você escrever muitos custom hooks:\n\n```tsx\nfunction tuplify\u003cT extends any[]\u003e(...elements: T) {\n  return elements;\n}\n\nfunction useArray() {\n  const numberValue = useRef(3).current;\n  const functionValue = useRef(() =\u003e {}).current;\n  return [numberValue, functionValue]; // o tipo fica (number | (() =\u003e void))[]\n}\n\nfunction useTuple() {\n  const numberValue = useRef(3).current;\n  const functionValue = useRef(() =\u003e {}).current;\n  return tuplify(numberValue, functionValue); // o tipo fica [number, () =\u003e void]\n}\n```\n\n\u003c/details\u003e\n\nSaiba que a equipe do React recomenda que custom hooks que retornam mais de dois valores usem objetos em vez de tuplas.\n\n## Leituras sobre Hooks + TypeScript (em inglês):\n\n- https://medium.com/@jrwebdev/react-hooks-in-typescript-88fce7001d0d\n- https://fettblog.eu/typescript-react/hooks/#useref\n\nSe você estiver escrevendo uma biblioteca de Hooks, não esqueça que você também deve expor os tipos para os usuários utilizarem.\n\n## Exemploes de bibliotecas React Hooks + TypeScript:\n\n- https://github.com/mweststrate/use-st8\n- https://github.com/palmerhq/the-platform\n- https://github.com/sw-yx/hooks\n\n[Tem algo a acrescentar? - link para o repositório original](https://github.com/typescript-cheatsheets/react-typescript-cheatsheet/issues/new).\n\n\u003c!--END-SECTION:hooks--\u003e","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftypescript-cheatsheets%2Freact-pt","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Ftypescript-cheatsheets%2Freact-pt","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftypescript-cheatsheets%2Freact-pt/lists"}