initial state react code example

Example 1: usestate hook

import React, { useState } from 'react';

function Example() {
  // Declare a new state variable, which we'll call "count"  
  const [count, setCount] = useState(0);
  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

Example 2: setstate react js

constructor(props) {
        super(props);
        this.state = {
            isActive: true,
        };
    }

    checkStatus = () => {
        this.setState({		// use this function
            'isActive' : !this.state.isActive,
        });
    }

Example 3: initialize state react

class App extends React.Component {
  constructor(props) {
    // Required step: always call the parent class' constructor
    super(props);

    // Set the state directly. Use props if necessary.
    this.state = {
      loggedIn: false,
      currentState: "not-panic",

      // Note: think carefully before initializing
      // state based on props!
      someInitialValue: this.props.initialValue
    }
  }

  render() {
    // whatever you like
  }
}