Skip to content

Instantly share code, notes, and snippets.

@sunmeat
Last active June 9, 2025 07:20
Show Gist options
  • Save sunmeat/9f7005818d5d69b495fefc29771601c8 to your computer and use it in GitHub Desktop.
Save sunmeat/9f7005818d5d69b495fefc29771601c8 to your computer and use it in GitHub Desktop.
сравнение жизненных циклов
import React, {useState, useEffect} from 'react';
import './App.css';
// время с микросекундами
const getTimeWithMicroseconds = () => {
const now = new Date();
const micros = Math.floor(performance.now() * 1000) % 1000000;
return `${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}:${now.getSeconds().toString().padStart(2, '0')}.${micros.toString().padStart(6, '0')}`;
};
// функциональный компонент кнопки
const FunctionalButton = ({width, height, color, text}) => {
const [clickCount, setClickCount] = useState(0);
useEffect(() => {
console.log('функциональная кнопка смонтирована ' + getTimeWithMicroseconds());
return () => {
console.log('функциональная кнопка размонтирована ' + getTimeWithMicroseconds());
};
}, []);
useEffect(() => {
console.log('функциональная кнопка ' + getTimeWithMicroseconds() + ' обновлена с clickCount =', clickCount);
}, [clickCount]);
// useEffect с зависимостью [clickCount] срабатывает при каждом рендере, даже с начальным clickCount = 0
const handleClick = () => {
setClickCount(clickCount + 1);
};
return (
<div className="button-container">
<button
className="custom-button"
style={{width, height, background: `linear-gradient(135deg, ${color}, ${color}CC)`}}
onClick={handleClick}
>
{text}
</button>
<p className="click-text">Functional Button Clicks: {clickCount}</p>
</div>
);
};
// классовый компонент
class ClassButton extends React.Component {
constructor(props) {
super(props);
this.state = {
clickCount: 0,
};
}
componentDidMount() {
console.log('классовая кнопка смонтирована ' + getTimeWithMicroseconds());
}
componentDidUpdate(prevProps, prevState) {
if (prevState.clickCount !== this.state.clickCount) {
console.log('классовая кнопка обновлена ' + getTimeWithMicroseconds() + ' с clickCount =', this.state.clickCount);
}
// в классе componentDidUpdate не вызывается при монтировании, что делает его более "строгим" — он логирует только реальные изменения состояния
}
componentWillUnmount() {
console.info('классовая кнопка размонтирована ' + getTimeWithMicroseconds());
}
handleClick = () => {
this.setState({clickCount: this.state.clickCount + 1});
};
// HMR (Hot Module Replacement) — функция Vite, которая обновляет код в реальном времени
// при сохранении файлов, не перезагружая всю страницу, но может вызывать временное размонтирование/монтирование компонентов
render() {
const {width, height, color, text} = this.props;
return (
<div className="button-container">
<button
className="custom-button"
style={{width, height, background: `linear-gradient(135deg, ${color}, ${color}CC)`}}
onClick={this.handleClick}
>
{text}
</button>
<p className="click-text">Class Button Clicks: {this.state.clickCount}</p>
</div>
);
}
}
const App = () => {
return (
<div className="app-container">
<FunctionalButton
width="200px"
height="50px"
color="#4CAF50"
text="Functional Button"
/>
<ClassButton
width="200px"
height="50px"
color="#2196F3"
text="Class Button"
/>
</div>
);
};
export default App;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment