React Hooks
React Hooks are functions that let you use state and other React features in functional components. They were introduced in React 16.8 to allow developers to manage component state and lifecycle methods without writing class components.
Common Hooks
Section titled “Common Hooks”- useState: Allows you to add state to functional components.
- useEffect: Lets you perform side effects in functional components, such as data fetching or subscribing to events.
- useContext: Provides access to the context value for a given context.
- useReducer: A more advanced alternative to
useStatefor managing complex state logic. - useRef: Allows you to create a mutable reference that persists across renders.
- useMemo: Memoizes a computed value to optimize performance.
- useCallback: Memoizes a callback function to prevent unnecessary re-creations.
- useLayoutEffect: Similar to
useEffect, but fires synchronously after all DOM mutations. - useImperativeHandle: Customizes the instance value that is exposed when using
refwithforwardRef. - useTransition: Allows you to manage state transitions and prioritize updates for better user experience.
- useDeferredValue: Returns a deferred version of a value that will defer updates to improve performance.
- useId: Generates a unique ID that can be used for accessibility attributes or other purposes.
- useActionState: Manages state for actions, typically used in concurrent React to handle transitions and updates.
- useFormStatus: Provides the status of a form, typically used to track submission state and validation status.
Rules of Hooks
Section titled “Rules of Hooks”- Only call hooks at the top level of a component or custom hook.
- Only call hooks from React functional components or custom hooks.
- Do not call hooks inside loops, conditions, or nested functions.
Custom Hooks
Section titled “Custom Hooks”Custom hooks are functions that start with “use” and allow you to extract and reuse hook logic across multiple components. They follow the same rules as regular hooks.
Example:
import { useState, useEffect } from "react";
function useWindowWidth() { const [width, setWidth] = useState(window.innerWidth);
useEffect(() => { const handleResize = () => setWidth(window.innerWidth); window.addEventListener("resize", handleResize); return () => window.removeEventListener("resize", handleResize); }, []);
return width;}