Synchronizing with Effects
What are Effects and how are they different from events?
Rendering code
pure
Event handlers
side effects
Effects let you specify side effects that are caused by rendering itself, rather than by a particular event.
Effects run at the end of a commit after the screen updates.
You might not need an Effect
How to write an Effect
Step 1: Declare an Effect
Step 2: Specify the Effect dependencies
code:jsx
function VideoPlayer({ src, isPlaying }) {
const ref = useRef(null);
useEffect(() => {
if (isPlaying) {
ref.current.play();
} else {
ref.current.pause();
}
return <video ref={ref} src={src} loop playsInline />;
}
Step 3: Add cleanup if needed
in development React remounts every component once immediately after its initial mount.
code:jsx
useEffect(() => {
const connection = createConnection();
connection.connect();
return () => {
connection.disconnect();
}
}, []);
How to handle the Effect firing twice in development?
React intentionally remounts your components in development to find bugs
Putting it all together
React always cleans up the previous render’s Effect before the next render’s Effect.