Understanding Side Effects in React: A Guide with TypeScript
In React, side effects refer to anything that affects something outside the scope of a function component, such as updating the DOM, fetching data, or interacting with external APIs. While React encourages declarative programming, side effects are often inevitable when building interactive UIs. Properly managing these effects is crucial for maintaining predictable(testable) and maintainable applications.
What are Side Effects in React?
In React, side effects typically occur when a component interacts with external systems or modifies shared states. Examples include:
- Fetching data from an API.
- Updating a DOM element directly.
- Logging information to an external service.
- Setting up subscriptions or timers.
React's
useEffect
hook is the primary tool for handling side effects in functional components.
Fetching Data
Fetching data is a common side effect. Here’s how you can use useEffect to fetch data in a React component:
In this example:
- The useEffect hook fetches user data when the component mounts.
- The empty dependency array ([]) ensures the effect runs only once.
- The setUsers function modifies the state, which is a controlled side effect.
Cleanup with Side Effects
Some side effects, like subscriptions or timers, require cleanup to prevent memory leaks. React allows you to return a cleanup function from useEffect
.
In this example:
- An interval is created in the useEffect hook.
- The cleanup function clears the interval when the component unmounts, preventing memory leaks.
Conditional Effects
Sometimes, effects depend on specific state or prop changes. This is where dependencies come into play.
In this example:
- The useEffect hook re-runs only when the query state changes.
- The dependency array [query] ensures unnecessary API calls are avoided.
Avoiding Unnecessary Re-Renders
React re-renders components when states or props change, which can trigger effects unnecessarily. Using tools like useCallback and useMemo can optimize performance.
useCallback memoizes the logCount function, ensuring it only updates when count changes. This prevents unnecessary re-creation of the function and optimizes the effect's behavior.
Learn more about useEffect
Share with your network: