Introduced in React 16.8, Hooks are functions that let you "hook into" React state and lifecycle features from functional components. Examples include useState, useEffect, useContext, useRef, and useMemo.
Because React relies on the internal execution order of functions to track hook state behind the scenes, you must adhere strictly to The Two Rules of Hooks.
22// Put conditions INSIDE the hook, not around it!
23if(userId){
24// Fetch user data...
25}
26},[userId]);
27
28if(!userId)return<p>Please select a user.</p>;
29
30return<div>{user?.name}</div>;
31}
Why does this rule exist?
React does not track hooks by name or ID. Instead, React maintains an internal array / linked list of hook cells for each component instance. On every render, React matches each hook call with the next cell in the list. If a hook is skipped inside an if block, every subsequent hook shifts out of position, permanently corrupting the component's state!
3. Rule 2: Only Call Hooks from React Functions
Do NOT call Hooks from regular JavaScript functions.
You must only call Hooks from:
1
React Functional Components: Functions that return JSX and start with an uppercase letter.
2
Custom Hooks: Functions whose names start with use (e.g., useFetch, useAuth, useLocalStorage).
1// ❌ FORBIDDEN: Calling hook from a plain helper function