React #6 - How to use State in Class Based Component
Let's Build With Code Let's Build With Code
178 subscribers
41 views
0

 Published On Sep 24, 2024

Click to watch React Playlist:    • React  

To view the code of this tutorial. Please visit this Github link:
https://github.com/lets-build-with-co...

In React, state is a built-in object that allows components to create and manage their own data. State is used to store information that can change over the lifetime of a component, and when the state changes, the component re-renders to reflect those changes.

Key Concepts of State

Initialization:
In class components, state is typically initialized in the constructor.
In functional components, state is initialized using the useState hook.

Updating State:
State should be updated using the setState method in class components or the updater function from useState in functional components.
Directly modifying the state (e.g., this.state.value = newValue) is not recommended as it won’t trigger a re-render.

Reactivity:
When state changes, React automatically re-renders the component to reflect the new state.


Why we need to use state in instead of regular variable

Regular variables do not trigger a re-render when they change. React is unaware of changes to these variables, so the UI does not update automatically.

Regular variables do not have lifecycle management. They are simply values that change without any built-in mechanism to notify React of these changes.

Regular variables can lead to inconsistent and unpredictable behavior, especially in complex applications where multiple components interact.

show more

Share/Embed