React Hooks: useState

From React there is a new way of managing state in functional components, using hooks. One of it is useState where we can get and set state values in functional components.

To utilize useState in our functional components we need to understand its parts. There are two important parts, the variable from useState and function which set the said variable. These two parts are destructured array values from useState

const [theVariable, setTheVariable] = React.useState('initial value')

The useState accept initial value which we can define. theVariable will contain the state in the useState then the setTheVariable is a function which accept value that set theVariable

A more complete functional component example utilizing useState as follows:

import React from "react";

export default function App() {
  const [buttonToggle, setButtonToggle] = React.useState(false);

  return (
    <div className="App">
      <button
        style={{ backgroundColor: buttonToggle ? "transparent" : "yellow" }}
        onClick={() => {
          setButtonToggle(!buttonToggle);
        }}
      >
        Toggle
      </button>
    </div>
  );
}

Here the useState contains the boolean value which is used as the toggle indicator for the button Toggle.

Reference:

  • https://reactjs.org/docs/hooks-state.html

2 thoughts on “React Hooks: useState”

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.