DEV Community

chantastic
chantastic

Posted on

4

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:

Image of Datadog

The Future of AI, LLMs, and Observability on Google Cloud

Datadog sat down with Google’s Director of AI to discuss the current and future states of AI, ML, and LLMs on Google Cloud. Discover 7 key insights for technical leaders, covering everything from upskilling teams to observability best practices

Learn More

Top comments (1)

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

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

πŸ‘‹ Kindness is contagious

Engage with a sea of insights in this enlightening article, highly esteemed within the encouraging DEV Community. Programmers of every skill level are invited to participate and enrich our shared knowledge.

A simple "thank you" can uplift someone's spirits. Express your appreciation in the comments section!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found this useful? A brief thank you to the author can mean a lot.

Okay