import React, { useState, useEffect } from 'react'; export default function Welcome() { const [message, setMessage] = useState('Loading...'); useEffect(() => { setMessage('Hello, friend!'); }, []); return <h1>{message}</h1>; }
The component first renders with 'Loading...'. Then useEffect runs after mounting and updates the message to 'Hello, friend!'. This triggers a re-render showing the updated message.
useEffect with an empty dependency array runs only once after the component mounts. Other hooks either run on every render or during initialization.
import React, { useState, useEffect } from 'react'; export default function Loop() { const [count, setCount] = useState(0); useEffect(() => { setCount(count + 1); }); return <p>{count}</p>; }
Without a dependency array, useEffect runs after every render. Inside it, setCount updates state, causing another render, creating an infinite loop.
Only an empty array as the second argument makes useEffect run once after mounting. Omitting it or using other values causes different behaviors.
import React, { useState, useEffect } from 'react'; export default function Counter() { const [count, setCount] = useState(0); useEffect(() => { setCount(c => c + 1); setCount(c => c + 1); }, []); return <div>{count}</div>; }
Both setCount calls use functional updates, so React applies them in order, resulting in count increasing by 2 after mounting.
