useState Hook

Learn how the “useState” hook in functional components can replace “this.setState” functionality for a React class component. This lesson will examine its syntax, usage, and it will also provide examples.

What is it?

Start by looking at how the state is managed by using a class.

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      items: []
    };
  }
  
  setItems = items => {
    this.setState(items);
  }
  
  render() {
    // some code here
  }
}

Here this.state is being used to initialize items and this.setState is used to update the state.

With useState hook, replace this.state and this.setState with a single hook call. The above example will reflect this when using the useState hook to manage items.

const App = () => {
  const [items, setItems] = useState([]);

  return (
    // some code
  );
};

As seen by the example, the useState hook initializes the state and provides a callback to update the state in a single line of code.

When do we use it?

Anytime a functional component needs to hold the internal state, use the useState hook to remember the state. In other words, create stateful logic by using the useState hook.

Syntax

const [state, setState] = useState(INITIAL_STATE);

The useState hook only takes one argument which is the value of the initial state.

It returns an array with two items in it:

  1. The first item in this array is a variable that holds the current value of the state.
  2. The second item is a function for updating the state variable with the new value.

“Array Destructuring” syntax from ES6 is being used to assign the array items to state and setState variables. In theory, it is possible to do this to achieve the same result:

const stateArray = useState(INITIAL_STATE);

const state = stateArray[0];
const setState = stateArray[1];

However, it is recommended to use ES6 syntax because it is much easier to read and a wider community is using useState hook in this way.

Create a free account to view this lesson.

By signing up, you agree to Educative's Terms of Service and Privacy Policy