loading...

Track State with React.useState

chantastic profile image Michael Chan ・1 min read

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()

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

React.useState()
// => [undefined, function]

It takes a default value as an argument.

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

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

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>
  );
}

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:

Discussion

pic
Editor guide
Collapse
fantasticsoul profile image
幻魂

Hi, dear friend, I recommend you have a try with concent) , which is born for build large scale and high performance react app.

here is online demos:
js ver: codesandbox.io/s/concent-guide-xvcej
ts ver: codesandbox.io/s/concent-guide-ts-...
function component and class component share business logic code easily, including their life-cycle methods.