The React team at Facebook announced Hooks earlier this year. React lifecycles enable you to manipulate data within components. With the recent addition of hooks, you can now replace repetitive code within your components.
Every component goes through the cycle of mounting, updating and umounting.
The render()
method is a requirement of a component in React.
Below are examples of lifecycle methods which enable you to manipulate data within your app in multiple different ways.
In this lifecycle you can use setState
to update the state after the component mounts.
componentDidMount() {
this.setState({
number: 10
})
}
If you want to update the component after props have changed within your component, you would need the following code.
componentDidUpdate(prevProps) {
if(this.props.propName !== prevProps.propName) {
//the computation you intend to do
}
}
This is called just before the component is unmounted. Usually used if you need to do any cleanup actions.
componentWillUnmount() {
window.removeEventListener('resize', this.resizeListener)
}
Hooks enable you to be able to organise your code in a more logical way and enable you to cut out repitive code from your program
useEffect
is short for use side effect - it enables you to be able to program a function, which can be used when something changes in your application. The useEffect
hook is a combination of componentDidMount
and componentDidUpdate
.
componentDidMount() {
console.log('example')
}
componentDidUpdate() {
console.log('example')
}
useEffect(() => console.log('example'))