An Introduction to useState

Iain Robertson
3 min readFeb 22, 2021

In the world of React Hooks, useState is the one most commonly used, and by far the most important to grasp when transitioning from class components to functional components. It allows for state management within our functional component, and permits the dynamic rendering of the UI based upon reactive data. It lays the groundwork for the comprehension and implementation of further React Hooks. In this overview we are going to be discussing the very basics of how to import, implement, and modify useState in a React component.

Import

There is more than one way to import the useState hook at the top of a react component, but the use of brackets specifying which hooks you are importing is a particularly straightforward option, and is easily expanded as more hooks are added to a given component.

Implementation

Following the successful import of our useState Hook, the next step is to implement the hook in order to create a piece of state for the component to keep track of. In this instance, we are goin to assemble a hypothetical counter that can increment with a button click. When we declare state with the useState hook, the format allows us to create the name of the state, the function with which we can alter it, and the initial value of the state all within a single line of code. In the line: const [count, setCount] = useState(0), we are declaring the name, count, in the first value in the array, and the function, setCount, in the second. We are also declaring the initial value of the variable count as 0, by placing that value within the parentheses of useState itself.

Modification

Now that we have a variable assigned to state and the function with which to alter that state, it is now time to incorporate those elements into our counter component. As illustrated above, by using our defined state variable, count, and function, setCount, within our JSX, we can begin including the functionality of a dynamically rendered and re-rendered counter into our component, which is accomplished by calling setCount within our button’s onClick.

useState is the cornerstone of React Hook implementation, and although we have only begun to cover the basics, once it is combined with other hooks such as useEffect, and the highly flexible power of the component life cycle, we begin to be able to use these state management basics to build powerful and dynamic functionality into our web apps. We are also able to write significantly more legible and streamlined code in a functional component than was previously possible, and it is entirely thanks to the development and implementation of these Hooks. Join us next time, where we will be delving into other hooks and the basics of their implementation.

--

--