Skip to main content

State

Initialize State Within a Component

import * as React from 'react';
import { useState } from 'react';

function Example() {
// Declare a new state variable, which we'll call "count"
const [count, setCount] = useState(0);
class Example extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0
};
}
  • State doesn’t need to be defined as an Object within a functional component.
  • State does need to be defined as an Object within a class component.

useState Hook

The useState hook is used within functional components and returns a pair of values: the current state and a function that updates it.

import * as React from 'react'
import { 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>
);
}

Setting and Updating State in a Class Component

class Example extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0
};
}

render() {
return (
<div>
<p>You clicked {this.state.count} times</p>
<button onClick={() => this.setState({ count: this.state.count + 1 })}>
Click me
</button>
</div>
);
}
}