React Mastery / React Hooks

useState Hook

What is useState?

The useState Hook is a special function in React that lets function components have their own state — so they can “remember” values and update the UI automatically whenever those values change.

Before hooks, only class components could have state. Now, any functional component can track and update information!


How Does useState Work?

  1. Import from React:

    import { useState } from 'react';
  2. Initialise state:

    const [value, setValue] = useState(initialValue);
    • value is the current state.

    • setValue is a function to update that state.

    • initialValue is the starting value (used only on the first render).

  3. Update state:

    When you use setValue(newValue):

    • It schedules a re-render for the component.

    • The component redraws with the updated value.


Practical Example: Counter

Class Component:

class Counter extends React.Component {
  constructor() {
    super();
    this.state = { count: 0 };
    this.increment = this.increment.bind(this);
  }

  increment() {
    this.setState({ count: this.state.count + 1 });
  }

  render() {
    return <button onClick={this.increment}>
              Count: {this.state.count}
           </button>
  }
}

Functional Component with useState:

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

  return (
    <button onClick={() => setCount(count + 1)}>
      Count: {count}
    </button>
  );
}
  • No classes, binding, or this keyword needed!

  • Just state and set function, declared in one line.

  • Notice boilerplate: constructor, binding, this.state, this.setState.


Breaking Down the Syntax

  • Array destructuring:

    The hook returns a pair — [stateVariable, setFunction] — which you can name however you like.

  • Initial value:

    The initialValue is set only once (on the first render); later renders use the updated state.

  • Supported data types:

    You can store anything: numbers, strings, arrays, objects, or functions.


Key Rules of Hooks

  1. Call hooks at the top level of your component —

    • Not inside loops, conditional statements, or nested functions.

  2. Only use hooks in React function components or inside your own custom hooks.


Why Prefer useState Over Class State?

  • Cleaner and shorter code — Less boilerplate, easier to read.

  • No this confusion — No method binding or worrying about context.

  • Logic organization — You can group stateful logic right where it’s used.

  • Reusability — Easily extract logic as custom hooks for sharing between components.


Key Benefits

  • Modern React — useState is a foundation for React’s functional programming style.

  • Automatic UI updates — Changes to state always update the visible UI.

  • Flexible and powerful — Great for anything from simple counters to complex, interactive interfaces.