0
0
Reactframework~30 mins

What is useEffect in React - Hands-On Activity

Choose your learning style9 modes available
Understanding useEffect in React
📖 Scenario: You are building a simple React app that shows a message and updates the document title when the message changes.
🎯 Goal: Learn how to use the useEffect hook to perform side effects like updating the document title when state changes.
📋 What You'll Learn
Create a React functional component called MessageUpdater
Use useState to hold a message string
Use useEffect to update the document title whenever the message changes
Render an input box to change the message
Render the current message below the input
💡 Why This Matters
🌍 Real World
useEffect is used in React apps to run code that affects things outside the component, like updating the page title, fetching data, or setting timers.
💼 Career
Understanding useEffect is essential for React developers to handle side effects properly and build interactive, dynamic web applications.
Progress0 / 4 steps
1
Set up the message state
Create a React functional component called MessageUpdater. Inside it, use useState to create a state variable called message with initial value "Hello".
React
Need a hint?

Use const [message, setMessage] = useState("Hello") inside the component.

2
Add useEffect to update document title
Inside the MessageUpdater component, add a useEffect hook that updates document.title to the current message whenever message changes.
React
Need a hint?

Use useEffect(() => { document.title = message; }, [message]) to update the title when message changes.

3
Render input to change message
Render an input element inside MessageUpdater that updates the message state when the user types. Use value={message} and onChange to update message with setMessage.
React
Need a hint?

Use <input value={message} onChange={e => setMessage(e.target.value)} /> to let user change the message.

4
Display the current message below input
Below the input, render a <p> element that shows the current message inside the MessageUpdater component.
React
Need a hint?

Use <p>{message}</p> to show the message below the input.