DEV Community

Hannah Glazier
Hannah Glazier

Posted on • Edited on

React's useState Hook

Introduction

As you begin your journey into the world of React you will find there are many things that this framework simplifies. However, there are also some key components (no pun intended) that can be difficult to wrap your head around in the beginning. Things like syntax and JSX often solidify themselves through practice and repetition, but concepts like state and hooks can greatly hinder your learning progress if you do not have a strong foundational understanding. It is my aim to explain and simplify the concept of React state and discuss how to use the useState hook.

State

State is the special ingredient that gives React its reactiveness. It is the unique tool that enables React to re-render particular parts of a page or program, while leaving the rest unchanged. Technically speaking, state is a built in object in a React component. "The state object is where you store property values that belongs to the component.When the state object changes, the component re-renders." State makes React dynamic and hooks are what allow us to utilize (hook into) state.

useState Walkthrough

Hooks are built-in functions in React that allow us to manage and manipulate state. One of the most common hooks is the useState hook. "The useState() is a Hook that allows you to have state variables in functional components. " In order to access useState, we need to import it like so:

import React, { useState } from "react";
Enter fullscreen mode Exit fullscreen mode

Once imported, the useState function takes the initial state as an argument and returns an array that contains the current state and a setter function that will be used to update state. Some consideration should be taken when determining your initial state. It is important to ask yourself what type of data you would like to return, is it a string, a boolean, an array? Determining this from the beginning can help to avoid running into bugs later on.

const [state, setState] = useState(initialState)
Enter fullscreen mode Exit fullscreen mode
const [count, setCount] = useState(0)
Enter fullscreen mode Exit fullscreen mode

It is important to note that state must be initialized at the very top of the component.

function Counter() {
  const [count, setCount] = useState(0);

  return <button>{count}</button>;
}
Enter fullscreen mode Exit fullscreen mode

After we have initialized state at the top of the component, it is time to use our setter function!

  function increment() {
    setCount((count) => count + 1);
  }
Enter fullscreen mode Exit fullscreen mode

An important aspect of state is the fact that it is asynchronous. Because of this, it is important to use a callback function in your setter function when your state update is dependent on the previous state (like with a counter or like button). Using a callback makes it so your state is updated based on the previous state instead of continually updating the same initial state.

Finally, in order to implement your state on the DOM you will need to add it to your returned JSX. For our counter example, this would mean adding a onClick to our button that calls on our increment function and then adding the count as the button's text content.

return <button onClick={increment}>{count}</button>
Enter fullscreen mode Exit fullscreen mode

Make sure that you are encasing all javascript syntax inside of curly braces {} when you are applying them to your JSX. This can be an easy syntax step to forget!

When to use state

So now that we have a better understanding of how to use state, we need to learn how to determine when we should use state. The React docs give us three questions to ask ourselves when determining if something is state or not.

  • Is it passed in from a parent via props? If so, it probably isn’t state.
  • Does it remain unchanged over time? If so, it probably isn’t state.
  • Can you compute it based on any other state or props in your component? If so, it isn’t state.

All of these tests need to fail in order for something to be eligible for state. If it is inherited by a child from a parent component as a prop, it will be considered immutable and therefor not state. If it remains unchanged overtime it isn't state as there are no state-like changes to manage. Finally, if it can be computed in any other way, you won't want to use state.

Conclusion

React's state is a powerful feature that can give us a multitude of dynamic behaviors. State has the unique ability to re-render the specific parts of a page the need changes, and leave the rest untouched. State is managed with hooks like the useState hook and always initialized at the top of a React component. It is important to note that with the power of React state can come a lot of complexity and because of this state should be used sparingly. You should always ask yourself React's three state-determining questions before implementing a state hook.

Sources:

https://reactjs.org/docs/thinking-in-react.html
https://www.geeksforgeeks.org/what-is-usestate-in-react/
https://www.w3schools.com/react/react_state.asp

Top comments (0)