Re-rendering is how React updates what you see on the screen when data changes. It helps keep the app fresh and correct.
0
0
Re-rendering behavior in React
Introduction
When you want the screen to update after a user clicks a button.
When data from a server changes and you want to show the new info.
When a user types in a form and you want to show live feedback.
When a timer counts down and you want to show the current time.
When switching between different views or pages in your app.
Syntax
React
import React, { useState } from 'react'; function Component() { const [state, setState] = useState(initialValue); // When setState is called, React re-renders this component return <div>{state}</div>; }
Calling setState triggers React to re-render the component.
React only re-renders components whose state or props have changed.
Examples
Clicking the button updates
count, causing React to re-render and show the new count.React
import React, { useState } from 'react'; const [count, setCount] = useState(0); <button onClick={() => setCount(count + 1)}> Clicked {count} times </button>
Changing props also triggers re-rendering of the component.
React
function Greeting({ name }) { return <h1>Hello, {name}!</h1>; } // If <Greeting name="Alice" /> changes to <Greeting name="Bob" />, React re-renders Greeting.
Typing in the input updates state and re-renders the input with the new value.
React
import React, { useState } from 'react'; const [text, setText] = useState(''); <input value={text} onChange={e => setText(e.target.value)} />
Sample Program
This simple counter shows how clicking the button updates state and causes React to re-render the component, updating the displayed count.
React
import React, { useState } from 'react'; export default function Counter() { const [count, setCount] = useState(0); return ( <div> <p>You clicked {count} times</p> <button onClick={() => setCount(count + 1)}> Click me </button> </div> ); }
OutputSuccess
Important Notes
React re-renders components efficiently by only updating parts that changed.
Excessive re-rendering can slow your app, so keep state updates minimal.
Using React DevTools can help you see when components re-render.
Summary
React re-renders components when their state or props change.
Re-rendering updates the screen to show the latest data.
Use state setters like setState to trigger re-rendering.