0
0
Reactframework~5 mins

Updating phase in React

Choose your learning style9 modes available
Introduction

The updating phase in React happens when a component changes its data or properties. It helps the app show the latest information on the screen.

When a user types in a form and the app needs to show what they typed.
When new data arrives from the internet and the app updates the display.
When a button click changes what is shown on the page.
When a timer or clock updates every second.
When a parent component sends new information to a child component.
Syntax
React
import React, { useState, useEffect } from 'react';

function ComponentName(props) {
  const [state, setState] = useState(initialValue);

  useEffect(() => {
    // code to run after update
  }, [state, props]);

  return (
    <div>{state}</div>
  );
}
The updating phase happens when state or props change.
The useEffect hook can run code after updates when dependencies change.
Examples
Updates the count state when the button is clicked, causing the component to re-render.
React
import React, { useState } from 'react';

function Example() {
  const [count, setCount] = useState(0);

  return (
    <button onClick={() => setCount(count + 1)}>
      Clicked {count} times
    </button>
  );
}
This runs after the count state updates, logging the new value.
React
import React, { useEffect } from 'react';

function Example({ count }) {
  useEffect(() => {
    console.log('Count changed:', count);
  }, [count]);

  return null;
}
Sample Program

This component updates the displayed text as the user types. The useEffect logs each update to the console.

React
import React, { useState, useEffect } from 'react';

export default function UpdatingPhaseExample() {
  const [text, setText] = useState('Hello');

  useEffect(() => {
    console.log('Text updated to:', text);
  }, [text]);

  return (
    <div>
      <input
        aria-label="Input text"
        value={text}
        onChange={e => setText(e.target.value)}
        placeholder="Type something"
      />
      <p>You typed: {text}</p>
    </div>
  );
}
OutputSuccess
Important Notes

Updating happens automatically when state or props change.

Too many updates can slow the app, so update only when needed.

Use useEffect to run code after updates, like fetching data or logging.

Summary

The updating phase shows new data on the screen when state or props change.

Use useState to hold data and useEffect to react to changes.

Updating keeps your app interactive and fresh for users.