Welcome Guest! (App Version 3.1)

websitnero logo name

State

What is State?

State is data that is locally owned by a certain component and this component behaves and renders UI based on this data (inside state).

State helps the component in rendering data and deciding how it will behave with the end user on UI.

We can also say that State is an object where you can store data that is related to a certain component. Whenever the data inside state will change, the render() function will automatically be triggered and UI of component will be rendered again.

Creating state in Component

State can be created at 2 places in a component:

  1. Inside the class
  2. Inside the constructor of class

Adding state directly inside a Class Component:

class Person extends Component{
  state = {
    name: "Peter Martin",
    age: 29,
    country: "USA"
  }
}

Adding state inside the Constructor Function:

class Person extends Component{
  constructor(){
    super();
    this.state = {
      name: "Peter Martin",
      age: 29,
      country: "USA"
    }
  }
}

Changing state within Component

You can directly change the state as state.age = 30 but react refers this as bad. Instead, when you want to change some state, just use setState to do this.

App.js

import React from 'react';
import './App.css';
import Home from './components/home';

function App() {
  return (
    <div className="App">
      <Home></Home>
    </div>
  );
}

export default App;

Home.js

import React, {Component} from 'react';

class Home extends Component {

  state = {
    name: "Peter Martin",
    age: 29,
    country: "USA"
  }

  alpha = () => this.setState({age: 30})

  render(){
    return(
      <div>
        <p>{this.state.name}, {this.state.age}</p>
        <button onClick={this.alpha}>click me</button>
      </div>
    )
  }
}

export default Home;

Output

File Structure:

WebsiteNero is highly optimized for learning various website developing technlogies. We try our best to add maximum modules and examples to help learn the concepts clearly and vividly. We try to present all content and examples as simple as we can removing any complexity to hurdle easy understanding. We try best provide you with worthful content, but we cannot guarantee full correctness of all the content on this site. While using this website, you agree to have read and accepted all our terms of use and conditions, cookie, and privacy policy. Copyright, 2013-2018 by websitenero.com. All Rights Reserved.