CodeBlanks Logo Icon CodeBlanks

useEffect

Learn side effects with useEffect.

What is useEffect?

In React Native useEffect is a hook that manages side effects. A side effect is any operation outside rendering: data fetching, subscriptions, timers or manual network calls. It is called as useEffect(EffectCallback); EffectCallback is a function.

useEffect runs when the component appears on screen (mount). It runs after render, so it fires as state updates. Import the hook from the react package: import { useEffect } from "react";. useEffect lets you write async side effects safely.

The effect callback

The first argument of useEffect is the effect callback; it is a function. React calls it after the component renders. Inside, you make side effect calls such as console.log, fetch or setInterval.

The effect callback runs after every render by default. To change this, you pass a second argument called the dependency array; we will see it in the next lesson. A function returned from the effect callback is called a cleanup and runs before the component is removed.

Practice Log a message with useEffect

Write a Message component. Import useEffect; inside the effect callback log "Component mounted" with console.log. The component returns <Text>Hello</Text>.

Starter code

App.js
// Import useEffect
// write here

function Message() {
  // Log a message with useEffect
  // write here

  return <Text>Hello</Text>;
}

Sample solution

App.js
import { useEffect } from "react";
import { Text } from "react-native";

function Message() {
  useEffect(() => {
    console.log("Component mounted");
  });
  return <Text>Hello</Text>;
}

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What is useEffect used for?

App.js
useEffect(() => { /* ... */ });
  • To manage side effects Correct answer
  • To create state
  • To style components
  • For navigation

Explanation: useEffect manages side effects.

2 Import the hook

Question
import { ____ } from "react";
Answer
import { useEffect } from "react";

Explanation: The hook is named useEffect.

3 Match each piece to its role

Term Meaning
useEffect Side effect hook
EffectCallback Function that runs
mount Component appears
render Screen drawn

All lessons in Intermediate