useState() Hook

Overview

To this point, state has been owned and managed solely in Class based React components, using this.state with this.setState() and instance methods to manage it all.

Newer versions of React now allow for “function components” to also manage their own state, using a newly exposed API, called “Hooks”

Class Outline

Learning Objectives

Students will be able to

Describe and Define

Execute

Notes

Hooks

React hooks allow to to easily create and manage state in a functional component.

Hooks are JavaScript functions, but they impose additional rules:

Built In Hooks

useState()

Returns a stateVariable and setterFunction for you to use to manage state in a functional component

In this example …

How does this work?

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

 function Counter() {
   const [clicks, setClicks] = useState(0);

   return (
     <div>
       <h2>Button has been clicked {clicks} time(s)</h2>
       <button type="button" onClick={() => setClicks(clicks + 1)}>
         Update Count
       </button>
     </div>
   );
 }

 export default Counter;