Unlock React Power with useState

What is React useState Hook?

  • The useState hook is a function that allows you to add state to a functional component.
  • It is an alternative to the useReducer hook, preferred when a basic update is required.
  • useState Hooks are used to add state variables to the components. 

Basic Syntax

onst [state, setState] = useState(initialValue);
  • state: The current state value.

  • setState: Function to update the state.

  • initialValue:The initial value of the state.

How Does useState() Work?

  • The useState() hook allows you to add state to functional components in React.
  1. Initialize State:
    • When you call useState(initialValue), it creates a state variable and an updater function.
      const [count, setCount] = useState(0);
  2. State is Preserved Across Renders:
    •  React remembers the state value between re-renders of the component.
    • Each time the component renders, React keeps the latest value of count.
  3. State Updates with the Updater Function:
    • When you call setCount(newValue), React updates the state, and it re-renders the component to reflect the new state value.
      <button onClick={() => setCount(count + 1)}>Increment</button>
  4. Triggers Re-render:
    • React will re-render only the component where useState it was used, ensuring your UI updates automatically when the state changes.

1. Counter App using useState

import React, { useState } from 'react';

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

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

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={increment}>Click me</button>
    </div>
  );
}

export default Counter;

In this example:

  1. useState(0): Initializes count with 0.
  2. setCount(count + 1): Updates the state by incrementing the current value by 1.
  3. setCount(count - 1): Decreases the state by 1.

2. Managing Form Input State

import React, { useState } from 'react';

function Form() {
    const [name, setName] = useState('');
    const [age, setAge] = useState('');
    const [submitted, setSubmitted] = useState(false);

    const handleSubmit = () => {
        setSubmitted(true);
    };

    return (
        <div>
            <input
                type="text"
                value={name}
                onChange={(e) => setName(e.target.value)}
                placeholder="Enter your name"
            />
            <input
                type="number"
                value={age}
                onChange={(e) => setAge(e.target.value)}
                placeholder="Enter your age"
            />
            <button onClick={handleSubmit}>Submit</button>
            {submitted && <p>Form Submitted!</p>}
        </div>
    );
}

export default Form;

In this example:

  1. useState(''): Initializes name and age with an empty string.
  2. onChange={(e): setName(e.target.value)}: Updates name state as the user types.
  3. onChange={(e): setAge(e.target.value)}: Updates age state as the user types.
  4. setSubmitted(true): Marks the form as submitted.

Key Points

  • You can use useState Multiple times in one component for different state variables.

  • State updates are asynchronous — React batches them.

  • The initial state can be any data type: number, string, object, array, etc.

Final Thoughts on useState Hook in React

The useState Hook is the foundation of state management in React functional components. It's simple yet powerful, allowing your UI to respond dynamically to user actions and data changes. By understanding how it works and following best practices, you can build clean, reactive, and maintainable components with ease​​​​​​​.​​​​​​​