Skip to content

Instantly share code, notes, and snippets.

@ibare
Last active November 7, 2024 06:36
Show Gist options
  • Save ibare/48ac81373b30a1348c9c23099bea823d to your computer and use it in GitHub Desktop.
Save ibare/48ac81373b30a1348c9c23099bea823d to your computer and use it in GitHub Desktop.
React function component vs. class component
import React, { useState } from 'react';
import ClassClock from './ClassClock';
import FunctionClock from './FunctionClock';
import ClassTodo from './ClassTodo';
import FunctionTodo from './FunctionTodo';
function App() {
const [visibleClock, setVisibleClock] = useState(true);
const [clockColor, setClockColor] = useState('black');
const toggleClock = () => setVisibleClock(!visibleClock);
const changeClockColor = (color) => setClockColor(color);
const colors = ['black', 'red', 'green', 'blue', 'purple'];
return (
<div>
<h1>My Todo</h1>
<input type="checkbox" checked={visibleClock} onChange={toggleClock} /> Show Clock
<div>
{colors.map((color, index) => (
<button key={index} onClick={() => changeClockColor(color)}>{color}</button>
))}
</div>
{visibleClock && <><ClassClock color={clockColor} /> <FunctionClock color={clockColor} /></>}
<ClassTodo />
<FunctionTodo />
</div>
)
}
export default App;
import React from 'react';
export default class ClassClock extends React.Component {
constructor(props) {
super(props);
this.timerId = null;
this.colorTimerId = null;
this.state = {
color: this.props.color || 'black',
date: new Date()
};
}
componentDidMount() {
console.log('componentDidMount');
this.timerID = setInterval(() => this.tick(), 1000);
}
componentDidUpdate(prevProps) {
if (prevProps.color !== this.props.color) {
if (this.colorTimerId) {
clearTimeout(this.colorTimerId);
}
this.colorTimerId = setTimeout(() => {
this.setState({ color: this.props.color });
}, 1000);
}
}
componentWillUnmount() {
console.log('componentUnmount');
clearInterval(this.timerID);
}
tick() {
this.setState({ date: new Date() });
}
render() {
return (
<h1 style={{ color: this.state.color || 'black' }}>
C: {this.state.date.toLocaleTimeString()}
</h1>
)
}
}
import React from 'react'
export default class ClassTodo extends React.Component {
constructor(props) {
super(props)
this.ref = React.createRef();
this.state = {
todoText: '',
items: [],
}
}
updateTodo = (event) => {
this.setState({
todoText: event.target.value
})
}
addItem = () => {
const { items, todoText } = this.state
this.setState({
items: [...items, { todo: todoText, complete: false }],
todoText: '',
})
}
deleteItem = (index) => {
this.setState({
items: this.state.items.filter((item, i) => i !== index)
})
}
render() {
return (
<div>
<div>
<input type="text" ref={this.ref} value={this.state.todoText} onChange={this.updateTodo} />
<button onClick={this.addItem}>Add</button>
</div>
<ul>
{this.state.items.map((item, index) => (
<li key={index}>
<input type="checkbox" />
{item.todo}
<button onClick={() => this.deleteItem(index)}>X</button>
</li>
))}
</ul>
</div>
)
}
}
import React, { useState, useEffect } from 'react';
export default function Clock({ color = 'black' }) {
const [date, setDate] = useState(new Date());
const [displayColor, setDisplayColor] = useState(color);
useEffect(() => {
console.log('useEffect');
const timerID = setInterval(() => {
setDate(new Date());
}, 1000);
return () => {
console.log('useEffect unmount');
clearInterval(timerID);
}
}, []);
useEffect(() => {
console.log('useEffect color');
const colorTimeout = setTimeout(() => {
setDisplayColor(color);
}, 1000);
return () => clearTimeout(colorTimeout);
}, [color]);
return (
<h1 style={{ color: displayColor }}>
F: {date.toLocaleTimeString()}
</h1>
);
}
import { useState, useRef } from 'react';
export default function FunctionTodo() {
const ref = useRef(null);
const [todoText, setTodoText] = useState('');
const [items, setItems] = useState([]);
const addItem = () => {
setItems([...items, { todo: todoText, complete: false }]);
setTodoText('');
}
const updateTodo = (event) => {
setTodoText(event.target.value);
}
const deleteItem = (index) => {
setItems(items.filter((item, i) => i !== index));
}
return (
<div>
<div>
<input type="text" ref={ref} value={todoText} onChange={updateTodo} />
<button onClick={addItem}>Add</button>
</div>
<ul>
{items.map((item, index) => (
<li key={index}>
<input type="checkbox" />
{item.todo}
<button onClick={() => deleteItem(index)}>X</button>
</li>
))}
</ul>
</div>
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment