DEV Community

losetom
losetom

Posted on

useState() in React

React has hooks which allow programmers to access features of React without having to use classes. One of these hooks is called useState().

The first step to applying useState is by importing the hook to the file of your choosing, as seen in the example below.

import { useState } from "react";

The next step is to initialize the useState hook that was just imported by calling it in our function component. useState will accept an initial state and then return two values: the current state and a function that updates the state.

import { useState } from "react";

function Counter() {
const [count, setCount] = useState(0);
}

The first value here is count, which is our current state. The second value is setCount, a function which will update state based on the user input.

Finally, we set the initial state to a number value with useState(0). The parentheses can hold a string, boolean, arrays, objects, or any combination of these values.

To make this useState functional, we can add a click event and a button to make this work.

import { useState } from "react";

function Counter() {
const [count, setCount] = useState(0);
}

return (


setCount(count + 1)}> Click!


);
}

This code creates a button that holds an initial state of 0 and will count upward from that value of 0 every time the button is clicked.

Resources

https://reactjs.org/docs/hooks-state.html

https://www.w3schools.com/react/react_usestate.asp

AWS Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Top comments (0)

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

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay