Before getting to Effects, you need to be familiar with two types of logic inside React components:
Rendering code (introduced in Describing the UI)
lives at the top level of your component.
This is where you take the props and state, transform them, and return the JSX
you want to see on the screen. Rendering code must be pure.
→ Like a math formula, it should only *calculate*
the result, but not do anything else.
Event handlers (introduced in Adding Interactivity) are nested functions
Sometimes this isn’t enough. Consider a ChatRoom
component that must connect to the chat server whenever it’s visible on the screen. Connecting to a server is not a pure calculation (it’s a side effect) so it can’t happen during rendering. However, there is no single particular event like a click that causes ChatRoom
to be displayed.
<aside> 💡 Effects let you specify side effects that are caused by rendering itself, rather than by a particular event
</aside>
Sending a message
in the chat is an *event*
However, setting up a server connection
is an *Effect*
because it should happen no matter which interaction caused the component to appear. Effects
run at the end of a commit after the screen updates.
→ This is a good time to synchronize
the React components with some external system (like network or a third-party library).
Don’t rush to add Effects to your components.
step out
” of your React codesynchronize
with some external system.
If your Effect only adjusts some state based on other state, you might not need an Effect.
To write an Effect, follow these three steps:
Declare an Effect.
— By default, your Effect
will run after every render.