Data Analyse Breda

React Hooks: useState, what is it and how can you use it?

This series of posts explains what React Hooks are and how you can use them. In this post we zoom in on useState, on the most commonly used hooks within React.

This is the start of a series of posts. In the next posts we will discuss other hooks such as useMemo, useEffect, and useHistory.

What are React Hooks?

Let’s first explain what hooks are. Hooks split a component in multiple functions.This enables developers to change the state of a component without changing the hierarchy.

Interecting with the state in Reacts class components became quite hard and cumbersome. React hooks enables the change of the state in functional components.

There are a few rules for using hooks:

  • They can only be used in functional components, not in class components.
  • Hooks can’t be conditional.
  • You can only use hooks at the top of the component.

React has a lot of out of the box hooks, but you can also create your own.

What is the useState hook?

The useState hook enables a developer to easily update the value of a constant with a function. The premise of this hook is very simple. You need to specify:

  • The current value.
  • A function that updates the current value.
  • Specify useState and the initial value.

The example below highlights the convention. A const is set for the currentvalue, along with a function name that changes the current value (in this case setCurrentvalue). In the useState hook you can specify your initial value.

const [currentvalue,setCurrentvalue] = useState("Initial value")

You can pick your own const names instead of currentvalue, and setCurrentvalue.

How can you use the useState hook?

The code sandbox below will bring the useState hook to life. To use this hook we need to:

  • Import the useState hook in our JS file.
  • Specify a const with the current value, the function that changes the current value, and the useState hook with the initial value.
  • Create a function that changes the const.

In the example below we have created a const called count. This is our current value. The const setCount is the function that changes this value. The usestate funtion is set to 0, so when we arrive on our page, the initial page is always set at 0.

We have also created a button. When we click this button, the setCount function is triggered, which takes the current value of count and adds 1.

Every time we click the button the constant is updated based on our function, and this is exactly what the useState hook aims to do!

In this example we use numbers, you can also replicate this example with strings, numbers, booleans, arrays, and objects.

useState in a nutshell

As displayed above, the useState hook makes it super easy to update the value or text within a constant. It is really easy to change UI values with the click of a button or a switch. In the next post we will zoom in to other hooks that can be used within React!

Geef een reactie