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

Top comments (0)