React Hooks Deep Dive

React Hooks Deep Dive

This post uses Code Hike's spotlight layout to explore four essential React hooks. Click any hook on the left to see its implementation and explanation on the right.

useState

The most fundamental hook. useState declares a state variable that persists across renders. The setter function triggers a re-render with the new value.

Returns a tuple of [currentValue, setterFunction]. The setter can take a value directly or a callback that receives the previous state.

useEffect

Runs side effects after render. The dependency array controls when the effect re-runs: on every render (no array), when dependencies change (with array), or only on mount (empty array).

The cleanup function runs before the effect re-fires and on unmount, preventing memory leaks from subscriptions and timers.

useRef

Creates a mutable ref object that persists across renders without causing re-renders when changed. Two primary use cases: accessing DOM elements and storing mutable values.

Unlike useState, updating a ref's .current property does not trigger a re-render, making it ideal for values you need to track but not display.

useMemo

Memoizes an expensive computation, recomputing only when dependencies change. Prevents unnecessary recalculations on every render.

Use it for computationally heavy operations like filtering large lists, complex math, or transforming data structures. Avoid overusing it for trivial calculations.

use-state.tsx
import { useState } from "react";
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
<button onClick={() => setCount((prev) => prev - 1)}>Decrement</button>
</div>
);
}