1import React, { useState, useEffect } from 'react';
2
3function FriendStatus(props) {
4 const [isOnline, setIsOnline] = useState(null); useEffect(() => { function handleStatusChange(status) { setIsOnline(status.isOnline); } ChatAPI.subscribeToFriendStatus(props.friend.id, handleStatusChange); return () => { ChatAPI.unsubscribeFromFriendStatus(props.friend.id, handleStatusChange); }; });
5 if (isOnline === null) {
6 return 'Loading...';
7 }
8 return isOnline ? 'Online' : 'Offline';
9}
1function ExampleWithManyStates() {
2 // Declare multiple state variables!
3 const [age, setAge] = useState(42);
4 const [fruit, setFruit] = useState('banana');
5 const [todos, setTodos] = useState([{ text: 'Learn Hooks' }]);
6 // ...
7}
1class Example extends React.Component {
2 constructor(props) {
3 super(props);
4 this.state = {
5 count: 0
6 };
7 }
8
9 componentDidMount() { document.title = `You clicked ${this.state.count} times`; } componentDidUpdate() { document.title = `You clicked ${this.state.count} times`; }
10 render() {
11 return (
12 <div>
13 <p>You clicked {this.state.count} times</p>
14 <button onClick={() => this.setState({ count: this.state.count + 1 })}>
15 Click me
16 </button>
17 </div>
18 );
19 }
20}
1useEffect(() => {
2 document.title = `You clicked ${count} times`;
3}, [count]); // Only re-run the effect if count changes
1componentDidUpdate(prevProps, prevState) {
2 if (prevState.count !== this.state.count) {
3 document.title = `You clicked ${this.state.count} times`;
4 }
5}