The heart of React - that's the state. It is an object which makes your component active and dynamic. This post will improve or build your understanding of this abstract topic for the most developer. As always, let's dive in!
I am gonna take in mind that you already know what are props - if no check my series (What the React), since the best way to understand the state is by comparing it to props.
Props | State |
It is an object passed to a component by its parent component. It can be used with all kinds of components | It is an object which is directly initialized and managed by the component where it is created. The state is possible inside a stateful component(class). However, hooks male it possible to defined and manage state in any kinds of components. |
Both state and props are the most important features of React component, and they're the only ones that can trigger re-rendering of the page content.
How to implement and use state in Class Components?
import React form 'react';
class Bapp etends React.componentt {
// when we use class component we need to extend React.comp...
// this gived us access to the lifecycle method like render()
state = { // we just assign state to an object
btClicked: false,
justNum: '5',
justSth: [23, 12, 79]
}
clickHandler = () => {// invoked on button click
this.setState(( state, props) => ({btnClicked: true}) );
// the proper way we change state. (NEVER STATE.PROP = X)
// thi is going to trigger a page re-render
console.log(this.state)
// the way we access state. we can also access its properties this way: this.state.just Numb (5)
}
render () => {
<button onClick={this.clickHandler}>Blah Blah </button>
)
}
}
export default Bapp;
// on clicking the button, the state is going to change which triggers a content re-render.
Thank You for Reading 🤩