DEV Community

Huy Do
Huy Do

Posted on

State Hook

Hooks let you use state and other React features without writing a class.

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>
  );
}
Enter fullscreen mode Exit fullscreen mode

React class

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>
    );
  }
}
Enter fullscreen mode Exit fullscreen mode

Hooks and Function Components

We can use these functions components in React. These are stateless components. They can be called function component Hooks don't work inside class. We can use them instead of writing classes.

const Example = (props) => {
  // You can use Hooks here!
  return <div />;
}
Enter fullscreen mode Exit fullscreen mode
function Example(props) {
  // You can use Hooks here!
  return <div />;
}
Enter fullscreen mode Exit fullscreen mode

If you want to add state to function component. You can add Hook useState function to it instead of converting it to a class.

import React, { useState } from 'react';

function Example() {
  // Declare a new state variable, which we'll call "count"
  const [count, setCount] = useState(0);
Enter fullscreen mode Exit fullscreen mode

Variable count could be called by anything. useStae is used as same asthis.state` provides in a class. State variables are preserved by React.

The argument to useState() Hook is the initial state. We can pass string or number as an argument for example 0 is initial state. We can call `useState() twice if we need to state two different values in state.

The state variable count was declare and set it to 0. React will remember the current value between re-renders, and provide the most recent one to our function. If we want to update the current count, we can call setCount.

Updating State

In a class, we need to call this.setState() to update the count state. In a function, we already have setCount and count as variables we don't need this

References:
https://reactjs.org/docs/hooks-state.html

Top comments (0)