Frontend - React Hooks
Introduced in React 16.8, Hooks are functions that let you "hook into" React state and lifecycle features from elegant functional components. They replaced clunky class components.
The Most Important Hooks for Interviews
1. useState
Manages reactive data. When the state changes, React re-renders the component.
const [cameraEnabled, setCameraEnabled] = useState(false);
// To toggle: setCameraEnabled(!cameraEnabled)
2. useEffect
Handles side effects (fetching APIs, subscribing to WebSockets, talking to hardware). It runs after the render is complete.
useEffect(() => {
// 1. Setup Phase
const ws = new WebSocket('ws://factory-server');
// 2. Cleanup Phase (runs when component unmounts to prevent memory leaks!)
return () => {
ws.close();
};
}, []); // 3. Dependency Array (empty [] means it only runs once on mount)
3. useRef
Holds a mutable reference that does not trigger a re-render when updated. Often used to grab raw HTML elements—such as a <canvas> element to draw machine vision bounding boxes directly—or to store a mutable value (like a WebSocket instance).
4. useCallback & useMemo (Performance)
When a parent component re-renders, it deletes and recreates all of its functions and variables.
useCallback: Caches a function between re-renders so child components don't unnecessarily spin.useMemo: Caches the result of a heavy calculation between re-renders. (e.g.,useMemo(() => heavyMatrixMath(data), [data]))
Custom Hooks
You can combine standard hooks into your own reusable functions. This is perfect for abstracting complex data-fetching or WebSocket syncing away from your clean UI components.
// Abstracting WebSocket logic entirely into a custom hook
export function useEdgeTelemetry(url) {
const [fps, setFps] = useState(0);
useEffect(() => {
const ws = new WebSocket(url);
ws.onmessage = (event) => {
const data = JSON.parse(event.data);
if (data.type === 'telemetry') setFps(data.fps);
};
return () => ws.close(); // Cleanup
}, [url]);
return { fps };
}
// In your UI: const { fps } = useEdgeTelemetry("ws://cam-01");
Rules of Hooks (Interview Trap!)
- Never call Hooks inside loops, conditions, or nested functions. React relies on the exact order in which hooks are called to preserve state arrays correctly under the hood. Only call them at the top level of the component!
- Only call Hooks from React Function Components.