1. Home
  2. Coding Hub
  3. Coding Notes
  4. React
  5. Usestate Hook
45% OFFBLACK FRIDAY SALE
Sale ends in
03Days
13Hrs
19Mins
39Secs
Claim
  1. Home
  2. Coding Hub
  3. Coding Notes
  4. React
  5. Usestate Hook

Limited time offer

45% OFF

BLACK FRIDAY SALE

Sale ends in

03Days
13Hrs
19Mins
39Secs
Claim
HTMLCSSJavaScriptPythonJavaC++React.jsSQLNext.jsNode.js
Underrated CoderUnderrated Coder
Underrated CoderUnderrated Coder
Resources
  • Coding Hub
  • Roadmap
  • DSA Sheet
  • Coding Notes
  • Coding Quiz
  • Code Compiler
  • Coder AI
Interview Preparation
  • 1:1 Mentorship
  • Interview Q&A
Community
  • Blog
  • Coder Community
Help & Support
  • Contact Us
  • Troubleshooting
  • Report a Bug
HTMLCSSJavaScriptPythonJavaC++React.jsSQLNext.jsNode.js
Outline
React IntroductionSetup & ViteJSX SyntaxVirtual DOMFunction ComponentsComponent TreeReact Fragments
Passing PropsDestructuring PropsChildren PropConditional RenderingList RenderingReact KeysCSS Modules
Event HandlingSynthetic EventsState BasicsuseState HookState BatchingObject StateArray State
useEffect HookDependency ArrayCleanup FunctionsData FetchingStrict Mode
useRef HookPassing Refs (forwardRef)useReducer HookCustom HooksuseId Hook
Prop Drilling ProblemContext APIuseContext HookRedux IntroZustand Alternative
React Router DOMRoute ParametersNested RoutesControlled InputsReact Hook Form
React.memouseMemo HookuseCallback HookCode Splitting (lazy)Bundle Size Optimization
React Server ComponentsClient ComponentsSuspense for Data FetchingNext.js App RouterServer ActionsuseTransition HookReact 19 Forms (useActionState)
React.js

useState Hook

Overview

useState is the absolute most fundamental Hook in React. A 'Hook' is simply a special built-in React function that allows you to 'hook into' React's internal engine from inside a Function Component.

useState takes one argument (the initial starting value) and returns an array containing exactly two elements. Because it returns an array, we universally use Array Destructuring to immediately grab both elements.

The first element is the current state value (the data). The second element is the setter function (the ONLY tool allowed to change the data).

You can call useState as many times as you want in a single component to track different pieces of independent data (e.g., username, password, isLoading).

Syntax

The Anatomy of useState
javascript
import { useState } from 'react';

function ProfileEditor() {
  // Using Array Destructuring to extract the two items returned by useState()
  // [current_data_variable, update_function] = useState(starting_value)
  const [username, setUsername] = useState("Guest");
  const [age, setAge] = useState(18);
  const [isEditing, setIsEditing] = useState(false);

  return (
    <div>
      <p>Name: {username}</p>
      <button onClick={() => setUsername("Kartik")}>
        Change Name
      </button>
    </div>
  );
}

Common Pitfalls

  • Calling hooks conditionally: Hooks must be called at the absolute top level of your component. You cannot put useState inside an if statement, inside a for loop, or inside a nested function. React relies on the exact order of hook calls across re-renders to maintain state mapping.

Interview Questions

Why does useState return an array instead of an object?

If it returned an object, like { state, setState }, you would be forced to rename the variables every time you used the hook multiple times in one file using clunky syntax: const { state: age, setState: setAge } = useState(). By returning an array, Array Destructuring allows you to cleanly name the variables whatever you want immediately based on their position: const [age, setAge] = useState().

What are the rules of Hooks?

1. Only call Hooks at the top level of a React Function Component (never inside loops, conditions, or nested functions). 2. Only call Hooks from React Function Components or custom Hooks (not from regular JavaScript functions).

Real-World Example

Multi-Step Form Logic: By storing currentStep in state, we can conditionally render completely different UI sections. When setCurrentStep is called, React instantly destroys Step 1 and renders Step 2 on the screen.

example
javascript
function SignupFlow() {
  // Tracking multiple pieces of state independently
  const [currentStep, setCurrentStep] = useState(1);
  const [email, setEmail] = useState("");
  
  const handleNext = () => {
    // We use the setter function to advance the UI
    setCurrentStep(currentStep + 1);
  };

  return (
    <div className="wizard">
      <h2>Step {currentStep} of 3</h2>
      
      {currentStep === 1 && (
        <input 
          type="email" 
          value={email}
          onChange={(e) => setEmail(e.target.value)} 
          placeholder="Enter email"
        />
      )}
      
      {currentStep === 2 && <p>Please create a password.</p>}
      
      <button onClick={handleNext}>Continue</button>
    </div>
  );
}

Check Your Knowledge

Test your understanding of useState Hook with these quick questions.

Question 1

Which of the following is the CORRECT way to update a state variable called 'score'?

Question 2

Can you place a `useState` call inside an `if` statement?

Take React Quiz
Outline
React IntroductionSetup & ViteJSX SyntaxVirtual DOMFunction ComponentsComponent TreeReact Fragments
Passing PropsDestructuring PropsChildren PropConditional RenderingList RenderingReact KeysCSS Modules
Event HandlingSynthetic EventsState BasicsuseState HookState BatchingObject StateArray State
useEffect HookDependency ArrayCleanup FunctionsData FetchingStrict Mode
useRef HookPassing Refs (forwardRef)useReducer HookCustom HooksuseId Hook
Prop Drilling ProblemContext APIuseContext HookRedux IntroZustand Alternative
React Router DOMRoute ParametersNested RoutesControlled InputsReact Hook Form
React.memouseMemo HookuseCallback HookCode Splitting (lazy)Bundle Size Optimization
React Server ComponentsClient ComponentsSuspense for Data FetchingNext.js App RouterServer ActionsuseTransition HookReact 19 Forms (useActionState)
React.js

useState Hook

Overview

useState is the absolute most fundamental Hook in React. A 'Hook' is simply a special built-in React function that allows you to 'hook into' React's internal engine from inside a Function Component.

useState takes one argument (the initial starting value) and returns an array containing exactly two elements. Because it returns an array, we universally use Array Destructuring to immediately grab both elements.

The first element is the current state value (the data). The second element is the setter function (the ONLY tool allowed to change the data).

You can call useState as many times as you want in a single component to track different pieces of independent data (e.g., username, password, isLoading).

Syntax

The Anatomy of useState
javascript
import { useState } from 'react';

function ProfileEditor() {
  // Using Array Destructuring to extract the two items returned by useState()
  // [current_data_variable, update_function] = useState(starting_value)
  const [username, setUsername] = useState("Guest");
  const [age, setAge] = useState(18);
  const [isEditing, setIsEditing] = useState(false);

  return (
    <div>
      <p>Name: {username}</p>
      <button onClick={() => setUsername("Kartik")}>
        Change Name
      </button>
    </div>
  );
}

Common Pitfalls

  • Calling hooks conditionally: Hooks must be called at the absolute top level of your component. You cannot put useState inside an if statement, inside a for loop, or inside a nested function. React relies on the exact order of hook calls across re-renders to maintain state mapping.

Interview Questions

Why does useState return an array instead of an object?

If it returned an object, like { state, setState }, you would be forced to rename the variables every time you used the hook multiple times in one file using clunky syntax: const { state: age, setState: setAge } = useState(). By returning an array, Array Destructuring allows you to cleanly name the variables whatever you want immediately based on their position: const [age, setAge] = useState().

What are the rules of Hooks?

1. Only call Hooks at the top level of a React Function Component (never inside loops, conditions, or nested functions). 2. Only call Hooks from React Function Components or custom Hooks (not from regular JavaScript functions).

Real-World Example

Multi-Step Form Logic: By storing currentStep in state, we can conditionally render completely different UI sections. When setCurrentStep is called, React instantly destroys Step 1 and renders Step 2 on the screen.

example
javascript
function SignupFlow() {
  // Tracking multiple pieces of state independently
  const [currentStep, setCurrentStep] = useState(1);
  const [email, setEmail] = useState("");
  
  const handleNext = () => {
    // We use the setter function to advance the UI
    setCurrentStep(currentStep + 1);
  };

  return (
    <div className="wizard">
      <h2>Step {currentStep} of 3</h2>
      
      {currentStep === 1 && (
        <input 
          type="email" 
          value={email}
          onChange={(e) => setEmail(e.target.value)} 
          placeholder="Enter email"
        />
      )}
      
      {currentStep === 2 && <p>Please create a password.</p>}
      
      <button onClick={handleNext}>Continue</button>
    </div>
  );
}

Check Your Knowledge

Test your understanding of useState Hook with these quick questions.

Question 1

Which of the following is the CORRECT way to update a state variable called 'score'?

Question 2

Can you place a `useState` call inside an `if` statement?

Take React Quiz

React.js coding notes for Indian students — 53 topics with syntax, pitfalls, interview Q&A, and inline quizzes.

Topics in React.js

  1. React Introduction
  2. Setup & Vite
  3. JSX Syntax
  4. Virtual DOM
  5. Function Components
  6. Component Tree
  7. React Fragments
  8. Passing Props
  9. Destructuring Props
  10. Children Prop
  11. Conditional Rendering
  12. List Rendering
  13. React Keys
  14. CSS Modules
  15. Event Handling
  16. Synthetic Events
  17. State Basics
  18. useState Hook
  19. State Batching
  20. Object State
  21. Array State
  22. useEffect Hook
  23. Dependency Array
  24. Cleanup Functions
  25. Data Fetching
  26. Strict Mode
  27. useRef Hook
  28. Passing Refs (forwardRef)
  29. useReducer Hook
  30. Custom Hooks
  31. useId Hook
  32. Prop Drilling Problem
  33. Context API
  34. useContext Hook
  35. Redux Intro
  36. Zustand Alternative
  37. React Router DOM
  38. Route Parameters
  39. Nested Routes
  40. Controlled Inputs
  41. React Hook Form
  42. React.memo
  43. useMemo Hook
  44. useCallback Hook
  45. Code Splitting (lazy)
  46. Bundle Size Optimization
  47. React Server Components
  48. Client Components
  49. Suspense for Data Fetching
  50. Next.js App Router
  51. Server Actions
  52. useTransition Hook
  53. React 19 Forms (useActionState)

Study next

  • All coding notes
  • React.js notes home
  • React certification quiz
  • Online compiler
  • Interview Q&A

React.js coding notes for Indian students — 53 topics with syntax, pitfalls, interview Q&A, and inline quizzes.

Topics in React.js

  1. React Introduction
  2. Setup & Vite
  3. JSX Syntax
  4. Virtual DOM
  5. Function Components
  6. Component Tree
  7. React Fragments
  8. Passing Props
  9. Destructuring Props
  10. Children Prop
  11. Conditional Rendering
  12. List Rendering
  13. React Keys
  14. CSS Modules
  15. Event Handling
  16. Synthetic Events
  17. State Basics
  18. useState Hook
  19. State Batching
  20. Object State
  21. Array State
  22. useEffect Hook
  23. Dependency Array
  24. Cleanup Functions
  25. Data Fetching
  26. Strict Mode
  27. useRef Hook
  28. Passing Refs (forwardRef)
  29. useReducer Hook
  30. Custom Hooks
  31. useId Hook
  32. Prop Drilling Problem
  33. Context API
  34. useContext Hook
  35. Redux Intro
  36. Zustand Alternative
  37. React Router DOM
  38. Route Parameters
  39. Nested Routes
  40. Controlled Inputs
  41. React Hook Form
  42. React.memo
  43. useMemo Hook
  44. useCallback Hook
  45. Code Splitting (lazy)
  46. Bundle Size Optimization
  47. React Server Components
  48. Client Components
  49. Suspense for Data Fetching
  50. Next.js App Router
  51. Server Actions
  52. useTransition Hook
  53. React 19 Forms (useActionState)

Study next

  • All coding notes
  • React.js notes home
  • React certification quiz
  • Online compiler
  • Interview Q&A