CodeBlanks Logo Icon CodeBlanks

Update

Learn the component update event.

Update

After a component mounts, a change to its state or props triggers the update phase. React calls the component again, computes the new JSX, and applies the changed parts to the screen. This redraw is called a re-render.

During an update, useEffect runs again if a value in its dependency array changed. An empty array runs only on mount; a filled array runs on every relevant change.

Re-render triggers

A re-render is triggered in three cases: a setState call, a parent re-render, or a Context value change. When a component changes its own state, both it and its children re-render.

Each render returns new JSX; React compares it with the old one and applies only the diff. So re-renders are cheap; the real cost lives in side effects and heavy computations.

Practice Track count changes

Log console.log('count: ' + count) whenever count changes. Use useEffect and put count in the dependency array.

Starter code

App.js
import React, { useState } from 'react';
import { Button, Text, View } from 'react-native';

export default function Counter() {
  const [count, setCount] = useState(0);
  // Log when count changes
  return (
    <View>
      <Text>{count}</Text>
      <Button title="Add" onPress={() => setCount(count + 1)} />
    </View>
  );
}

Sample solution

App.js
import React, { useState, useEffect } from 'react';
import { Button, Text, View } from 'react-native';

export default function Counter() {
  const [count, setCount] = useState(0);
  useEffect(() => {
    console.log('count: ' + count);
  }, [count]);
  return (
    <View>
      <Text>{count}</Text>
      <Button title="Add" onPress={() => setCount(count + 1)} />
    </View>
  );
}

Questions and answers

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

1 Filled dependency array

Question
useEffect(() => { save(count); }, ____);
Answer
useEffect(() => { save(count); }, [count]);

Explanation: The [count] array runs the effect when count changes.

2 Which of these does NOT trigger a re-render?

  • A setState call
  • A parent render
  • A Context value change
  • A sibling component rendering Correct answer

Explanation: Sibling components do not affect each other.

3 Re-render causes

Term Meaning
setState State change
prop Parent data
Context Global value
mount First render

All lessons in Intermediate