techStackGuru

React useState Hook


Function components can be tracked using the useState Hook in React. Components can be dynamically updated, making them responsive to user interactions by storing and updating their state.

State management has traditionally been possible only in class components, but hooks introduced in React 16.8 the capability to manage state in functional components as well. In useState, an initial state value is passed as a parameter, and the function returns an array that contains two elements: the current state value and the function that updates it.

This example illustrates how useState is used:


import React, { useState } from 'react';

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

  const increment = () => {
    setCount(count + 1);
  };

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={increment}>Increment</button>
    </div>
  );
} 

The first point in this example is initialized with the value zero using the useState hook. Each time the button is clicked, the count value is updated by the setCount function. React re-renders the component and displays the updated count each time setCount is called.

Toggle Button:

import React, { useState } from 'react';

function ToggleButton() {
  const [isOn, setIsOn] = useState(false);

  const toggle = () => {
    setIsOn(!isOn);
  };

  return (
    <div>
      <button onClick={toggle}>
        {isOn ? 'Turn Off' : 'Turn On'}
      </button>
      {isOn && <p>On!</p>}
    </div>
  );
} 

Toggle buttons can be managed with useState in this example. As soon as you click on the button, the current state is toggled between true and false. Initially, the state is set to false. In addition, the toggle button displays the message "On!".

Input Field:

import React, { useState } from 'react';

function InputField() {
  const [text, setText] = useState('');

  const handleChange = (e) => {
    setText(e.target.value);
  };

  return (
    <div>
      <input
        type="text"
        value={text}
        onChange={handleChange}
      />
      <p>Text: {text}</p>
    </div>
  );
}

This example shows how useState is used to manage an input fields state. Text state is initially set to an empty string. A handleChange function is called whenever a value is entered in the input field, updating the text state. After the text has been entered, it is displayed below the input field.

Dropdown Select:

import React, { useState } from 'react';

function DropdownSelect() {
  const [selectedOption, setSelectedOption] = useState('');

  const handleSelect = (e) => {
    setSelectedOption(e.target.value);
  };

  return (
    <div>
      <select value={selectedOption} onChange={handleSelect}>
        <option value="">Select an option</option>
        <option value="option1">Option 1</option>
        <option value="option2">Option 2</option>
        <option value="option3">Option 3</option>
      </select>
      <p>Selected Option: {selectedOption}</p>
    </div>
  );
} 

This example shows how to manage the state of a dropdown select component using useState. In the initial state, the string is empty. The handleSelect function is called when a value is chosen from the drop-down, updating the selectedOption state accordingly. After the select component has been selected, the selected option will be displayed below it.

This example shows how to increment a counter:

import React, { useState } from 'react';

function CounterWithStep() {
  const [count, setCount] = useState(0);
  const [step, setStep] = useState(1);

  const increment = () => {
    setCount(count + step);
  };

  const decrement = () => {
    setCount(count - step);
  };

  const handleStepChange = (e) => {
    setStep(Number(e.target.value));
  };

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={increment}>Increment</button>
      <button onClick={decrement}>Decrement</button>
      <input
        type="number"
        value={step}
        onChange={handleStepChange}
      />
    </div>
  );
}