1. The original intention of hooks design (why there are hooks)
Before React 16.8:
- Logic reuse → HOC / render props
- state management → class component
- Lifecycle → scattered in componentDidMount/update/unmount
- this points to complex
- Logic is scattered and difficult to maintain
Goals of Hooks:
- ✅ Logic reuse
- ✅ Function components have state
- ✅ Side effects logic can be combined
- ✅ Better tree shaking
2. Overview of Core Hooks
1️⃣ useState
const [state, setState] = useState(initialState)Key points
- setState is asynchronous batching (React 18 automatic batching)
- Updates may be merged
- Support functional updates
setCount(prev => prev + 1)Deep dive in interview
Why can't I write useState in the condition?
- The order of Hooks calling must be stable (depending on fiber’s hooks list)
2️⃣ useEffect
Side effect handling core API.
useEffect(() => {
// effect
return () => {
// cleanup
}
}, [deps])execution timing
- Executed after first rendering
- Execute after dependency changes
- Uninstall and execute cleanup
Important changes in React 18
- It will be executed twice in strict mode (development environment)
- Used to detect side effects and safety
useEffect vs useLayoutEffect
| useEffect | useLayoutEffect | |
|---|---|---|
| Timing | Usually after paint; interactions and other cases may run earlier | After DOM commit, before browser paint |
| Blocks paint | Usually not used to block paint | Blocks browser paint |
| Scenario | Request/Subscribe | DOM Reading and Writing |
3️⃣ useRef
const ref = useRef(null)Features:
- Do not trigger re-rendering
- save variable value
- DOM available
Advanced usage:
const latestFn = useRef(fn)
useLayoutEffect(() => {
latestFn.current = fn
}, [fn])Update the latest callback inside a component or custom Hook, then read latestFn.current from event handlers; initializing a ref alone does not keep it synchronized with fn.
4️⃣ useMemo
const memoValue = useMemo(() => compute(), [deps])- Caching calculation results
- Prevent double counting
- Used for object reference stability
⚠️ Abuse can increase memory pressure
5️⃣ useCallback
const memoFn = useCallback(() => {}, [deps])Essence:
useMemo(() => fn, deps)Purpose:
- Subcomponent React.memo optimization
- Event function reference is stable
6️⃣ useContext
const value = useContext(Context)Question:
- Any value changes → all consumers re-render
Solution:
- split context
- useContextSelector
- external state library
7️⃣ useReducer
const [state, dispatch] = useReducer(reducer, initialState)Suitable for:
- complex state
- Multi-field linkage
- Form management
Analogy:
- Redux Lite
3. React 18 new Hooks
useTransition
Solve the lag problem.
const [isPending, startTransition] = useTransition()- Mark low priority updates
- Does not block the UI
Suitable for:
- Search filter
- Large list rendering
useDeferredValue
const deferred = useDeferredValue(value)Delay updating a value.
useId
Solve the problem of SSR hydration id inconsistency.
4. The underlying principles of Hooks
Inside React:
- Each Fiber has a one-way linked list of hooks
- Each hook structure:
{
memoizedState,
queue,
next
}The calling sequence determines positioning:
useState()
useEffect()
useState()The order must be consistent.
Here's why:
❌ Hooks cannot be called in if
5. Closure trap problem (high frequency)
useEffect(() => {
setInterval(() => {
console.log(count)
}, 1000)
}, [])count is always the initial value.
Solution:
- Dependent array plus count
- useRef saves the latest value
- Use functional updates
6. Custom Hooks
essence
Functions + internal calls to other hooks
Example:
function useRequest(url) {
const [data, setData] = useState(null)
useEffect(() => {
fetch(url).then(r => r.json()).then(setData)
}, [url])
return data
}Advantages:
- Logic reuse
- separation of concerns
- Combinatorial programming
7. Performance optimization ideas
1️⃣ Reduce meaningless re-rendering
- React.memo
- useMemo
- useCallback
- Split components
2️⃣ State granularity control
- local state
- Avoid top-level large objects
3️⃣ Long list
- virtual list
- useTransition
- Tile rendering
8. Comparison with Vue3 Composition API
| React Hooks | Vue3 |
|---|---|
| useState | ref/reactive |
| useEffect | watchEffect |
| custom hook | composable |
| useMemo | computed |
| fiber scheduling | reactive dependency tracking |
The biggest difference:
- React depends on the calling order
- Vue depends on Proxy dependency collection
10. Final summary
Hooks are React's mechanism for implementing state and side effects management in functional components. The essence is to store states in the order of calls based on Fiber linked lists, and implement responsive updates through closures and scheduling systems.