There are many concepts you will learn in React. Below are three important core concepts you should understand no matter what.
Let’s get right into it.
Component lifecycle is the core concept of React framework.
A React app consists of many individual components. Like everything in this world, each React component has its own lifecycle. That means they are born, start living, and then die at some point.
Each part of a component’s life is defined as a method. They are called at different stages while the component is existing.
Depending on what stage you’re handling, you will do certain tasks to serve specific purposes.
So, what are those stages?
1. componentWillMount()
This method is invoked before rendering. You use this method to get everything ready before displaying any UI element on the screen.
The component is not mounted yet. There’s no DOM in this stage. You shouldn’t make any asynchronous actions or change data using this.setState()
. No need to rush, you will do all of them in the next stage.
2. componentDidMount()
After render()
done for the first time, componentDidMount()
function will be executed. This is when changes can occur.
Now, you can fetch data from API or update state.
To modify data in this stage, you can use setState()
method, which will trigger another rendering.
3. componentWillRecieveProps()
This stage takes place right after the props are updated and before the next render()
is executed.
4. shouldComponentUpdate()
You use this method to determine whether a component should be updated or not. The default value is true
.
For the sake of performance, if you are sure that a component doesn’t need to be updated, then return false
. That way it will remain the same as the previous state, no rendering happens.
5. componentWillUpdate()
This method will be invoked before rendering.
6. componentDidUpdate()
After rendering, this method will be called.
You can update DOM in this stage too. But remember to check prop changes from the previous state to make sure no infinite loop will occur.
7. componentWillUnmount()
When the component is unmounted from the DOM, this method will be called.
If there’s any resource you want to release, you should do it using this method.
#reactjs #react #javascript