DEV Community

Matheus Ricelly
Matheus Ricelly

Posted on

Introducing Hooks in React (useState)

Alt Text

Hey guys!

Although hooks are no longer a great novelty within React (since they have been introduced since version 16.8), there is still a large collection of documents that exemplify on the traditional model of development through classes in React components.

I will write a series of introductory articles talking about the main React Hooks, among them, the useState (which will be our first), useEffect and useContext, then we will pass through those a little more complex for some users, such as useRef, useCallback, useReducer, among others. You can also create your own hook, this is very useful in certain situations (we can see in a next publication, leave your comment).

Theory

What is a hook?

Well summarized, a hook is nothing more than a function that gives you access to certain features of a functional component of React (yes, functional component, since hooks do not work within classes), and that way you can access to your state and life cycle.

And to have a good performance as states and lifecycles are rendered in the component, Hooks have a basic rule that specifies that it should never be used within loops, conditional rules (if, else for example) or nested functions, be aware of this rule!

Hands-on

useState

const [state, setState] = useState(initialState);
Enter fullscreen mode Exit fullscreen mode

This hook is responsible for manipulating the state of your application. It returns to us an array where we have a value and a function that when invoked will have a responsibility to change the information of this value.

We can pass an initial value when the initial rendering of the component occurs. This value is the same signpost within the initial argument in useState (initialState).

In this example, setState is used when we want to update that state variable within the component. It receives the new value informed and instead of updating immediately, it queues that value, thus passing the most recent value to this variable, this process is well known in the react by immutability.

An alternative, and you can find in several codes, it is the possibility of invoking the function that updates the status with a callback, taking the same previous example, could refactor it like this:

setState(prevState => nextState);
Enter fullscreen mode Exit fullscreen mode

That way the new state based on the previous one returns. Due to immutability, this is widely used in some applications where we want to make some comparisons on state changes for screen animations, for example.

const [name, setName] = useState<string>('John Doe');
Enter fullscreen mode Exit fullscreen mode

Already when we use the TypeScript, we infer the state type as in the above example useState<string>('value'). However, it is worth mentioning, that for primary types (such as strings, number, boolean, for example) you do not need to make the type explicit because the typescript interpreter can dynamically define them, leaving that way, the cleaner code Thus avoiding an error if a different data type is informed.

A more complete example about using type in useState with TypeScript you can be below:

import React, { useState } from 'react'

type ProductProps = {
  id: number
  name: string
  price: number
}

export default function Product() {
  const [ product, setProduct ] = useState<ProductProps[]>([
    {
      id: 1,
      name: 'Samsung Galaxy S20',
      price: 1999
    },
    {
      id: 2,
      name: 'Headset Misoftsot LX-300',
      price: 79
    },
    {
      id: 3,
      name: 'Mouse Gamer Corsair',
      price: 449
    }
  ])

  return (
    <div>
      <ul>
        { 
          product.map(item => (
            <li key={item.id}>{item.name} - {item.price}</li>
          ))
        }
      </ul>
    </div>
  )
}
Enter fullscreen mode Exit fullscreen mode

Above, very simple, show how to pass an array of products, inside the useState. With this, in addition to testing the use of array (which is another type allowed inside the useState), we can verify how to proceed with this typing through the typescript and infer within the code perform the listing for view on the page.

Tips that are essential in using useState

As good practice, always try to call the useState Hooks at the beginning of the component. Even if you position it in different places, React will try to organize so that your code works, however, you will present several warnings in your devtools.

Avoid creating Usestate within loops, conditional or some nested function, this can cause various errors in the rendering of your component, damaging your project.

It's from this introductory line, that you can deepen a little more of your knowledge within React and React Hooks. Explore your knowledge and studies in this React functionality that allows you to help in various tasks in your applications. You can have all the information about Hooks in Official Documentation or a Detailed Reference of Usestate.


If you liked this article, be sure to share and comment. If you want to know a little more, change some ideas, you can leave the comments your opinion on the subject and even suggest something for the upcoming articles.

Enjoy and get to know a little of my jobs, visiting the site www.fsenaweb.me. It's has my portfolio, my social networks (including GitHub, where you have a few applications of examples to practice), and contacts links.


And that's it, until next time! My name is Matheus Ricelly, and for his attention, my thank you!

Top comments (0)