Lifecycle Methods in React JS
Lifecycle methods are methods that are called at different stages in the lifecycle of a component. They allow you to perform actions when a component is mounted, updated, or unmounted. Here's an example of a class component that uses lifecycle methods:
jsx
class Timer extends React.Component {
constructor(props) {
super(props);
this.state = { seconds: 0 };
}
componentDidMount() {
this.timerID = setInterval(() => this.tick(), 1000);
}
componentWillUnmount() {
clearInterval(this.timerID);
}
tick() {
this.setState({ seconds: this.state.seconds + 1 });
}
render() {
return (
<div>
<p>Seconds: {this.state.seconds}</p>
</div>
);
}
}
ReactDOM.render(
<Timer />,
document.getElementById('root')
);
In this example, the Timer component has three lifecycle methods:
componentDidMount: This method is called after the component is mounted in the DOM. In this example, it starts a timer that updates the state every second.
componentWillUnmount: This method is called just before the component is unmounted from the DOM. In this example, it stops the timer to prevent memory leaks.
render: This method is called whenever the component needs to be rendered.
These are just a few of the many topics and concepts involved in React JS. Hopefully these examples help you understand how React works and how it can be used to build complex UIs.
No comments:
Post a Comment