Sub topic 1
Rendering Should Be Pure
Prerequisites
Assume you know function components, JSX, props, useState, JavaScript closures, and basic browser APIs such as document.
Rendering Should Be Pure
A React render calculates what the user interface should look like from the component's current props and state. Rendering should be pure, meaning it returns the same result for the same inputs and does not change anything outside the component.
Do not start a timer, modify the DOM, or send a network request during rendering. React may render a component more than once before committing the result. Side effects during rendering can therefore happen at the wrong time or happen more than once.
What Counts as a Side Effect
A side effect is an operation that interacts with something outside the render calculation. Examples include:
- Changing
document.title - Adding an event listener
- Starting a timer
- Fetching data
- Subscribing to an external store
An event handler is often the best place for an effect caused directly by a user action. An effect is useful when the outside system must stay synchronized with the rendered component.
Your First `useEffect`
useEffect schedules a function to run after React commits the rendered output to the DOM.
import { useEffect, useState } from 'react';
export default function Counter() {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = `Clicked ${count} times`;
}, [count]);
return (
<button onClick={() => setCount(count + 1)}>
Clicked {count} times
</button>
);
}The effect runs after the initial commit and after any commit where count changed. It does not run while React is calculating JSX.
Dependencies: Controlling Re-runs
The second argument is the dependency array. It lists reactive values used by the effect.
[count]: run after the initial render and whencountchanges.[]: run after the initial render only, although development Strict Mode may test it more than once.- No array: run after every committed render.
Include every prop, state value, or function from the component that the effect reads. Missing a dependency can make the effect use an old value.
Exercise
Why does the counter effect include [count]?
Show answer
The effect reads count to build the document title, so count must be a dependency for the title to stay synchronized.