Escape hatches
Quick answer: Sometimes you must touch the DOM, network, or subscriptions—that is useRef and useEffect, plus when not to use an effect. This page links to a free scrim and Advanced React (Pro) for deeper patterns.
This page explains React’s escape hatches for work that does not belong in render alone: useRef for mutable values and DOM nodes without re-renders, useEffect for syncing with browsers, networks, and subscriptions after paint, and guidance on when an effect is the wrong tool (derive during render or handle in events instead).
Who This Is For
Learners following the React or Next.js roadmap.
1. References with Refs
Refs let a component hold some information that isn't used for rendering, like a DOM node or a timeout ID. Unlike state, updating a ref does not re-render your component.
Common use case: Focusing an input.
const inputRef = useRef(null);
function handleClick() {
inputRef.current.focus();
}
return <input ref={inputRef} />;
2. Synchronizing with Effects
useEffect lets you run code after rendering so you can synchronize your component with an external system.
Common Use Cases:
- Fetching data from an API.
- Subscribing to events (window resize, websockets).
- Manipulating the DOM manually.
The Syntax:
useEffect(() => {
// 1. Setup code (runs on mount)
const connection = createConnection();
connection.connect();
// 2. Cleanup code (runs on unmount/re-run)
return () => {
connection.disconnect();
};
}, []); // 3. Dependency array (when to re-run)
Learn it on Scrimba: -> Interactive Lesson: useEffect Syntax
3. You Might Not Need an Effect
Effects are powerful but easy to overuse. If you can calculate something during render, do not use an effect.
- ❌ Don't use effects to transform data for rendering. Use derived state instead:
// Wrong: effect to filter
const [filtered, setFiltered] = useState([]);
useEffect(() => { setFiltered(items.filter(i => i.active)); }, [items]);
// Right: compute during render
const filtered = items.filter(i => i.active);
- ❌ Don't use effects to handle user events. Click handlers are the right place. Effects run after render; events need immediate response.
- ❌ Don't use effects to sync with props. If a value can be computed from props, derive it in render.
We cover best practices and optimization in the Advanced React course.
Choose This If
Choose this page if: You're learning React or Next.js and want a docs-to-Scrimba roadmap.
Related Scrimba courses
Continue with Advanced React on Pro for custom hooks, performance, and larger app patterns (pricing).
Ready to Upgrade Your Learning?
Use our partner link to claim 20% off Scrimba Pro and unlock all courses and career paths.