DEV Community

chantastic
chantastic

Posted on

Track State with React.useState

To make state dynamic, we just need a function to update it.

React gives us this function via React.useState.

React.useState is a function.

React.useState()
Enter fullscreen mode Exit fullscreen mode

It returns an array that includes the current value and an updater function.

React.useState()
// => [undefined, function]
Enter fullscreen mode Exit fullscreen mode

It takes a default value as an argument.

React.useState("some default value")
// => ["some default value", function]
Enter fullscreen mode Exit fullscreen mode

We can use array destruct assignment to assign array elements to local variables.

let [value, setValue] = React.useState("default value")
// value => "default value"
// setValue => function
Enter fullscreen mode Exit fullscreen mode

Wee use these values in our components.

function App() {
  let [index, setIndex] = React.useState(0);

  return (
    <div>
      <button type="button" onClick={() => setIndex(index + 1)}>
        Next
      </button>

      <div>Current Index: 1</div>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

Give it a try

Use React.useState to update the Pokemon app in today's assignment sandbox:

Assignment

  1. Use the React.useState function to wrap our index state
  2. Use array destructuring assignment to name the first and second elements of the Array React.useState returns
  3. Use the setIndex function to respond to button clicks and update the index

Subscribe on YouTube:

Follow the 🧵 on Twitter:

Top comments (1)

Some comments may only be visible to logged-in visitors. Sign in to view all comments.