{"id":26178552,"url":"https://github.com/kareem-aez/react-hooks-cheat-sheet","last_synced_at":"2026-05-18T10:02:25.758Z","repository":{"id":273925010,"uuid":"921331154","full_name":"Kareem-AEz/React-Hooks-Cheat-Sheet","owner":"Kareem-AEz","description":"React Hooks are functions that let you use state and other React features without writing a class. They allow you to manage state and side effects in functional components, making your code cleaner and more reusable.","archived":false,"fork":false,"pushed_at":"2025-01-23T19:12:17.000Z","size":15,"stargazers_count":3,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-03-11T21:34:42.077Z","etag":null,"topics":["reacthooks","reactjs"],"latest_commit_sha":null,"homepage":"","language":null,"has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/Kareem-AEz.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2025-01-23T18:56:22.000Z","updated_at":"2025-02-16T12:25:07.000Z","dependencies_parsed_at":"2025-01-23T19:38:01.646Z","dependency_job_id":"b9712b37-21d4-469e-a9fa-36a4d0ccc383","html_url":"https://github.com/Kareem-AEz/React-Hooks-Cheat-Sheet","commit_stats":null,"previous_names":["kareem-aez/react-hooks"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/Kareem-AEz/React-Hooks-Cheat-Sheet","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Kareem-AEz%2FReact-Hooks-Cheat-Sheet","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Kareem-AEz%2FReact-Hooks-Cheat-Sheet/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Kareem-AEz%2FReact-Hooks-Cheat-Sheet/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Kareem-AEz%2FReact-Hooks-Cheat-Sheet/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Kareem-AEz","download_url":"https://codeload.github.com/Kareem-AEz/React-Hooks-Cheat-Sheet/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Kareem-AEz%2FReact-Hooks-Cheat-Sheet/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":33174091,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-05-18T09:27:30.708Z","status":"ssl_error","status_checked_at":"2026-05-18T09:27:28.300Z","response_time":71,"last_error":"SSL_connect returned=1 errno=0 peeraddr=140.82.121.5:443 state=error: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"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":["reacthooks","reactjs"],"created_at":"2025-03-11T21:29:05.994Z","updated_at":"2026-05-18T10:02:25.736Z","avatar_url":"https://github.com/Kareem-AEz.png","language":null,"funding_links":[],"categories":[],"sub_categories":[],"readme":"# React Hooks Cheat Sheet\n\nReact Hooks are functions that let you use state and other React features without writing a class. They allow you to manage state and side effects in functional components, making your code cleaner and more reusable.\n\n## 🚀 Your Ultimate Guide to Mastering React Hooks!\n\nThis repository is a comprehensive cheat sheet for React Hooks, designed to help developers understand and use hooks effectively in their projects. Whether you're a beginner or an experienced developer, this guide covers everything you need to know about React's powerful hooks API, including:\n\n- **useState** for state management\n- **useEffect** for side effects\n- **useRef** for mutable references\n- **useReducer** for complex state logic\n- **useContext** for global state sharing\n- **useMemo** and **useCallback** for performance optimization\n- **memo** for preventing unnecessary re-renders\n\nEach hook is explained with clear examples, best practices, and common pitfalls to avoid. Plus, the cheat sheet is structured for easy navigation, making it a handy reference for your day-to-day development.\n\n## Why Use This Cheat Sheet?\n\n✅ **Beginner-Friendly:** Perfect for developers new to React Hooks.  \n✅ **Quick Reference:** Easily find what you need with a well-organized table of contents.  \n✅ **Best Practices:** Learn how to use hooks effectively and avoid common mistakes.  \n✅ **Code Examples:** Practical examples to help you understand each hook in action.  \n\n## Table of Contents\n1. [useState](#1-usestate)\n2. [useEffect](#2-useeffect)\n3. [useRef](#3-useref)\n4. [useReducer](#4-usereducer)\n5. [useContext](#5-usecontext)\n6. [useMemo](#6-usememo)\n7. [useCallback](#7-usecallback)\n8. [memo](#8-memo)\n9. [Common Issues](#9-common-issues)\n10. [Custom Hooks](#10-custom-hooks)\n11. [Quick Reference Table](#11-quick-reference-table)\n12. [Version Compatibility](#12-version-compatibility)\n13. [Feedback Mechanism](#13-feedback-mechanism)\n\n---\n\n## 1. `useState`\n\nUsed for managing state in functional components.\n\n```javascript\nimport { useState } from 'react';\n\nfunction Counter() {\n  const [count, setCount] = useState(0);\n\n  const increment = () =\u003e setCount(prevCount =\u003e prevCount + 1);\n\n  return (\n    \u003cbutton onClick={increment}\u003eCount: {count}\u003c/button\u003e\n  );\n}\n```\n\n### Best Practices\n\n- **DO:** Use functional updates (`prevState`) when the new state depends on the old state.\n- **DO:** Initialize state with a function if the calculation is expensive.\n- **DON'T:** Update state directly (e.g., `count++` instead of `setCount(count + 1)`).\n\n### Common Pitfalls\n\n- Forgetting to use the functional form of `setState` when the new state depends on the previous state can lead to bugs.\n\n---\n\n## 2. `useEffect`\n\nPerforms side effects in functional components (e.g., fetching data, subscriptions).\n\n```javascript\nimport { useEffect, useState } from 'react';\n\nfunction UserProfile({ userId }) {\n  const [profile, setProfile] = useState(null);\n\n  useEffect(() =\u003e {\n    let isMounted = true;\n\n    fetch(`/api/user/${userId}`)\n      .then(response =\u003e response.json())\n      .then(data =\u003e {\n        if (isMounted) setProfile(data);\n      });\n\n    return () =\u003e {\n      isMounted = false;\n    };\n  }, [userId]);\n\n  return \u003cdiv\u003e{profile ? profile.name : 'Loading...'}\u003c/div\u003e;\n}\n```\n\n### Best Practices\n\n- **DO:** Include all dependencies in the dependency array to avoid stale closures.\n- **DO:** Clean up effects by returning a cleanup function (e.g., unsubscribing).\n- **DON'T:** Omit dependencies or add functions inline without wrapping them in `useCallback`.\n\n### Dependency Arrays Explained\n\n- An empty array (`[]`) means the effect runs only once after the initial render.\n- Specifying dependencies (e.g., `[userId]`) means the effect runs whenever those dependencies change.\n\n---\n\n## 3. `useRef`\n\nMaintains a mutable reference to an element or a value that doesn’t trigger re-renders.\n\n```javascript\nimport { useRef } from 'react';\n\nfunction TextInput() {\n  const inputRef = useRef(null);\n\n  const focusInput = () =\u003e inputRef.current.focus();\n\n  return (\n    \u003c\u003e\n      \u003cinput ref={inputRef} type=\"text\" /\u003e\n      \u003cbutton onClick={focusInput}\u003eFocus Input\u003c/button\u003e\n    \u003c/\u003e\n  );\n}\n```\n\n### Best Practices\n\n- **DO:** Use `useRef` for DOM elements or storing mutable values.\n- **DON'T:** Use `useRef` to store derived or computed state.\n\n---\n\n## 4. `useReducer`\n\nManages complex state logic with actions.\n\n```javascript\nimport { useReducer } from 'react';\n\nfunction counterReducer(state, action) {\n  switch (action.type) {\n    case 'increment':\n      return { count: state.count + 1 };\n    case 'decrement':\n      return { count: state.count - 1 };\n    default:\n      throw new Error(`Unhandled action type: ${action.type}`);\n  }\n}\n\nfunction Counter() {\n  const [state, dispatch] = useReducer(counterReducer, { count: 0 });\n\n  return (\n    \u003c\u003e\n      \u003cbutton onClick={() =\u003e dispatch({ type: 'decrement' })}\u003e-\u003c/button\u003e\n      \u003cspan\u003e{state.count}\u003c/span\u003e\n      \u003cbutton onClick={() =\u003e dispatch({ type: 'increment' })}\u003e+\u003c/button\u003e\n    \u003c/\u003e\n  );\n}\n```\n\n### Best Practices\n\n- **DO:** Use `useReducer` for state logic that involves multiple sub-values.\n- **DO:** Define actions and reducer logic separately for clarity.\n- **DON'T:** Use `useReducer` for simple state updates (prefer `useState`).\n\n### Example: To-Do List\n\n```javascript\nfunction todoReducer(state, action) {\n  switch (action.type) {\n    case 'add':\n      return [...state, action.payload];\n    case 'remove':\n      return state.filter(todo =\u003e todo.id !== action.payload);\n    default:\n      throw new Error(`Unhandled action type: ${action.type}`);\n  }\n}\n```\n\n---\n\n## 5. `useContext`\n\nShares state globally between components without prop drilling.\n\n### Setting Up Context with Best Practices\n\n```javascript\nimport { createContext, useContext, useState } from 'react';\n\nconst MyContext = createContext();\n\nexport function MyProvider({ children }) {\n  const [value, setValue] = useState('Default Value');\n\n  return (\n    \u003cMyContext.Provider value={{ value, setValue }}\u003e\n      {children}\n    \u003c/MyContext.Provider\u003e\n  );\n}\n\nexport function useMyContext() {\n  const context = useContext(MyContext);\n  if (!context) {\n    throw new Error('useMyContext must be used within a MyProvider');\n  }\n  return context;\n}\n```\n\n### Using the Custom Hook\n\n```javascript\nimport { MyProvider, useMyContext } from './MyContext';\n\nfunction ChildComponent() {\n  const { value, setValue } = useMyContext();\n  return (\n    \u003cdiv\u003e\n      \u003cp\u003e{value}\u003c/p\u003e\n      \u003cbutton onClick={() =\u003e setValue('New Value')}\u003eChange Value\u003c/button\u003e\n    \u003c/div\u003e\n  );\n}\n\nfunction App() {\n  return (\n    \u003cMyProvider\u003e\n      \u003cChildComponent /\u003e\n    \u003c/MyProvider\u003e\n  );\n}\n```\n\n### Best Practices\n\n- **DO:** Wrap consumers with a provider to ensure proper context usage.\n- **DO:** Use custom hooks to encapsulate `useContext` for reusability.\n- **DON'T:** Use context for state that doesn’t need to be shared globally.\n\n---\n\n## 6. `useMemo`\n\nMemoizes expensive calculations to avoid re-computation.\n\n```javascript\nimport { useMemo } from 'react';\n\nfunction ExpensiveComponent({ items }) {\n  const total = useMemo(() =\u003e {\n    return items.reduce((sum, item) =\u003e sum + item.value, 0);\n  }, [items]);\n\n  return \u003cp\u003eTotal: {total}\u003c/p\u003e;\n}\n```\n\n### Best Practices\n\n- **DO:** Use `useMemo` to optimize expensive calculations.\n- **DON'T:** Overuse it for trivial computations—it adds unnecessary complexity.\n\n---\n\n## 7. `useCallback`\n\nMemoizes functions to prevent unnecessary re-creation.\n\n```javascript\nimport { useCallback, useState } from 'react';\n\nfunction ParentComponent() {\n  const [count, setCount] = useState(0);\n\n  const increment = useCallback(() =\u003e {\n    setCount(prevCount =\u003e prevCount + 1);\n  }, []);\n\n  return (\n    \u003cChildComponent onClick={increment} /\u003e\n  );\n}\n\nfunction ChildComponent({ onClick }) {\n  return \u003cbutton onClick={onClick}\u003eIncrement\u003c/button\u003e;\n}\n```\n\n### Best Practices\n\n- **DO:** Use `useCallback` when passing functions to child components.\n- **DON'T:** Use it for functions that don’t depend on props or state.\n\n---\n\n## 8. `memo`\n\nPrevents unnecessary re-renders by memoizing components.\n\n```javascript\nimport React, { memo } from 'react';\n\nconst ChildComponent = memo(({ value }) =\u003e {\n  console.log('Rendered');\n  return \u003cp\u003e{value}\u003c/p\u003e;\n});\n\nfunction ParentComponent() {\n  const [count, setCount] = useState(0);\n\n  return (\n    \u003c\u003e\n      \u003cChildComponent value={count} /\u003e\n      \u003cbutton onClick={() =\u003e setCount(count + 1)}\u003eIncrement\u003c/button\u003e\n    \u003c/\u003e\n  );\n}\n```\n\n### Best Practices\n\n- **DO:** Use `memo` to optimize performance for components with stable props.\n- **DON'T:** Overuse `memo`—it can make debugging harder.\n\n---\n\n## 9. Common Issues\n\n### Infinite Re-renders in `useEffect`\n\n- Ensure that dependencies are correctly specified to avoid infinite loops.\n\n### Stale State in `useState` or `useReducer`\n\n- Use functional updates to access the latest state.\n\n### Misuse of `useRef` for State Management\n\n- Remember that `useRef` does not trigger re-renders.\n\n---\n\n## 10. Custom Hooks\n\nCustom hooks allow you to extract component logic into reusable functions.\n\n### Example of a Custom Hook\n\n```javascript\nimport { useState, useEffect } from 'react';\n\nfunction useFetch(url) {\n  const [data, setData] = useState(null);\n  const [loading, setLoading] = useState(true);\n\n  useEffect(() =\u003e {\n    fetch(url)\n      .then(response =\u003e response.json())\n      .then(data =\u003e {\n        setData(data);\n        setLoading(false);\n      });\n  }, [url]);\n\n  return { data, loading };\n}\n```\n\n---\n\n\n## 12. Quick Reference Table\n\n| Hook        | Purpose                                   | Example Use Case                     |\n|-------------|-------------------------------------------|--------------------------------------|\n| `useState`  | Manage state in functional components     | Counter, form inputs                 |\n| `useEffect` | Perform side effects                      | Fetching data, subscriptions         |\n| `useRef`    | Access DOM elements or store mutable values | Focus input, store previous value    |\n| `useReducer`| Manage complex state logic                | To-do list, form validation          |\n| `useContext`| Share state globally                      | Theme, authentication                 |\n| `useMemo`   | Memoize expensive calculations            | Filtering or sorting large lists     |\n| `useCallback`| Memoize functions                        | Pass callbacks to child components    |\n| `memo`      | Prevent unnecessary re-renders           | Optimize performance of components    |\n\n---\n\n## 13. Version Compatibility\n\nThese hooks are available in React 16.8 and later. Ensure you are using a compatible version.\n\n---\n\n## 14. Feedback Mechanism\n\nIf you have suggestions or feedback, please open an issue or discussion on [GitHub](https://github.com/Kareem-AEz).\n\n---\n\n## Show Your Support\nIf you find this cheat sheet helpful, please give it a ⭐️ on GitHub! Your support motivates me to keep creating valuable resources for the developer community.\n\n\u003cdiv\u003e\n\n### Created with ❤️ by [Kareem](https://github.com/Kareem-AEz)\n\n\u003cimg src=\"https://img.shields.io/badge/React-Hooks-blue?style=for-the-badge\u0026logo=react\u0026color=61dafb\u0026labelColor=20232a\" alt=\"React Hooks\" /\u003e\n\n\u003c/div\u003e\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fkareem-aez%2Freact-hooks-cheat-sheet","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fkareem-aez%2Freact-hooks-cheat-sheet","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fkareem-aez%2Freact-hooks-cheat-sheet/lists"}