Hooks and useState in React
“A hook is a function provided by React that lets you hook into React features from your functions components”,
That is the definition of hooks gave by Dan Abramov, a software engineer at Facebook, in the React Conf 2018.
Hooks allows you to reuse stateful logic extracted out of components, testing it separately and reusing it between different components without introducing the wrapper hell.
Wrapper hell is a definition gave by Sophie Alpert (Also in the React Conf 2018) to big component trees that is difficult to follow the data flow through the app.
Let’s begin with probably the most used hook in React, the useState.
useState
We call it inside a function component to declare a new state variable to our component. It returns two “things”: The current state value and a function to update this value.
This hook accepts only one argument and is optional, the initial state. As its name suggests, it will be the initial value of the variable that is being created.
Usage
To implement the useState hook, we will create a simple counter component with a h1 tag that will display the value and a button to increment the counter (Fig 1).
If you try run this code, you will see that every time we increment the counter value, we can see the value changing in the browser. This "live change" is because we declare our counter value as a state of our component, so when we cause a change to its state (Like setCounter(counter + 1)), we are basically telling React: "Hey, we need display the new value of the counter, render it again!".
If you pass your mouse on the counter variable you will see that it type was automatically assumed by the type of the variable we initialize it.
In case you are working in a React project using Typescript, you can also pass the Type of your variable to the useState hook (Fig 2).
The useState is a powerful and indispensable tool in React projects, put it to good use but be careful to not break your app with unnecessary renders.
I hope this article helped you somehow in your study of React universe, any suggestion is welcome, thanks for your attention and never forget, don’t stop learning.