Popular Searches
Popular Course Categories
Popular Courses

Initializing State

Initializing State

State Management with useState

Initializing State in React JS

Initializing State in React means assigning the initial value to a state variable when a component is rendered for the first time. React's useState() Hook is commonly used to initialize and manage state in functional components. Initial state can store numbers, strings, booleans, arrays, objects, or other JavaScript values.

Learn more: JustAcademy React JS Training Course | Register for React JS Course Demo


1. What Is State in React?

State is data that a React component remembers between renders. It is used to manage changing information such as counters, form inputs, selected items, login status, and menu visibility.

When state is updated using its setter function, React can render the component again to display the updated value.

Example

import { useState } from 'react';
function App() {
  const [count, setCount] = useState(0);
  return (
    <div>
      <h2>Count: {count}</h2>
      <button onClick={() => setCount(count + 1)}>
        Increase
      </button>
    </div>
  );
}
export default App;

Explanation: The initial value of count is 0. When the user clicks the button, setCount() updates the state and React displays the new count.


2. What Is Initializing State?

Initializing state means providing the starting value that a state variable should have when its component is first rendered.

For example, a counter may start at 0, a name field may start with an empty string, and a menu visibility variable may start with false.

const [count, setCount] = useState(0);
const [name, setName] = useState('');
const [isVisible, setIsVisible] = useState(false);
  • count starts at 0.
  • name starts as an empty string.
  • isVisible starts as false.

3. Understanding the useState() Hook

useState() is a React Hook that allows functional components to declare and manage state.

Syntax

const [state, setState] = useState(initialValue);
Part Description
useState() React Hook used to declare state.
initialValue The value used to initialize the state on the component's first render.
state The current state value.
setState The setter function used to request a state update.

The initial value is used during initialization. On subsequent renders, React provides the current stored state rather than resetting it to the original value.


4. Initializing State with Different Data Types

4.1 Initializing a Number

Numbers are useful for counters, scores, quantities, and pagination.

import { useState } from 'react';
function Counter() {
  const [count, setCount] = useState(0);
  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>
        Increase
      </button>
    </div>
  );
}
export default Counter;

Initial state: 0. Each click increases the displayed value by one.

4.2 Initializing a String

Strings are commonly used for names, search queries, messages, and input fields.

import { useState } from 'react';
function UserName() {
  const [name, setName] = useState('Guest');
  return (
    <div>
      <p>Welcome, {name}</p>
      <button onClick={() => setName('Rahul')}>
        Change Name
      </button>
    </div>
  );
}
export default UserName;

Initial state: 'Guest'. Clicking the button changes the name to 'Rahul'.

4.3 Initializing a Boolean

Booleans represent two possible values: true and false. They are useful for toggles, modal visibility, dropdowns, and login status.

import { useState } from 'react';
function ToggleMessage() {
  const [isVisible, setIsVisible] = useState(false);
  return (
    <div>
      <button onClick={() => setIsVisible(!isVisible)}>
        Toggle Message
      </button>
      {isVisible && <p>Welcome to React!</p>}
    </div>
  );
}
export default ToggleMessage;

Initial state: false. The message is hidden initially and appears when the state becomes true.

4.4 Initializing an Array

Arrays are useful for lists of products, tasks, users, categories, and notifications.

import { useState } from 'react';
function TodoList() {
  const [todos, setTodos] = useState(['Learn HTML', 'Learn CSS']);
  function addTodo() {
    setTodos([...todos, 'Learn React']);
  }
  return (
    <div>
      <ul>
        {todos.map((todo, index) => (
          <li key={index}>{todo}</li>
        ))}
      </ul>
      <button onClick={addTodo}>Add Todo</button>
    </div>
  );
}
export default TodoList;

Initial state: An array containing two tasks. The spread operator creates a new array when adding another task.

4.5 Initializing an Object

Objects allow related values to be grouped together, such as a user's name, email, and age.

import { useState } from 'react';
function UserProfile() {
  const [user, setUser] = useState({
    name: 'Amit',
    age: 22
  });
  function updateAge() {
    setUser({ ...user, age: 23 });
  }
  return (
    <div>
      <p>Name: {user.name}</p>
      <p>Age: {user.age}</p>
      <button onClick={updateAge}>Update Age</button>
    </div>
  );
}
export default UserProfile;

Initial state: An object containing name and age. The spread operator preserves the other properties while updating the age.


5. Initializing State Without a Value

If no initial value is supplied, useState() initializes the state to undefined.

const [value, setValue] = useState();

For clearer and more predictable code, explicitly provide a suitable initial value whenever possible.

const [name, setName] = useState('');
const [user, setUser] = useState(null);
const [items, setItems] = useState([]);

Choose the initial value according to how the data will be used. For example, use an empty array for a list and an empty string for a text input.


6. Initializing State with null

null is useful when a value is intentionally absent at the beginning, such as a user profile that has not been selected yet.

import { useState } from 'react';
function Profile() {
  const [user, setUser] = useState(null);
  return (
    <div>
      {user ? (
        <p>Welcome, {user.name}</p>
      ) : (
        <p>No user selected.</p>
      )}
      <button onClick={() => setUser({ name: 'Priya' })}>
        Select User
      </button>
    </div>
  );
}
export default Profile;

Initially, user is null, so the component displays the fallback message. After selecting a user, it displays the user's name.


7. Lazy Initialization of State

Sometimes calculating an initial state is expensive. For example, a function may process a large list or calculate an initial value from existing data. In such cases, pass an initializer function to useState().

Regular initialization

const [items, setItems] = useState(createInitialItems());

Here, createInitialItems() is evaluated whenever the component function executes, even though React uses its result only for the initial state.

Lazy initialization

function createInitialItems() {
  return ['HTML', 'CSS', 'JavaScript'];
}
function App() {
  const [items, setItems] = useState(createInitialItems);
  return (
    <ul>
      {items.map((item) => (
        <li key={item}>{item}</li>
      ))}
    </ul>
  );
}

In this example, createInitialItems is passed as a function reference without parentheses. React calls the initializer when initializing the state rather than calling it on every render.

Important: An initializer function should be pure and should not perform side effects. In development Strict Mode, React may call it twice to help detect unintended side effects.


8. Initializing State from Props

A component can use a prop as its initial state value. However, the state is initialized only on the component's first render. If the prop changes later, the existing state does not automatically update.

import { useState } from 'react';
function Counter({ initialCount }) {
  const [count, setCount] = useState(initialCount);
  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>
        Increase
      </button>
    </div>
  );
}
export default Counter;

If initialCount is 5 when the component first renders, the state begins at 5. Later changes to the prop do not reset the state automatically.

If the component should reset whenever a particular identity changes, you can render it with a different key. React will then treat it as a new component and initialize its state again.


9. Initializing Multiple State Variables

A component can call useState() multiple times to manage separate pieces of state.

import { useState } from 'react';
function RegistrationForm() {
  const [name, setName] = useState('');
  const [email, setEmail] = useState('');
  const [isSubscribed, setIsSubscribed] = useState(false);
  return (
    <div>
      <input
        value={name}
        placeholder="Enter name"
        onChange={(e) => setName(e.target.value)}
      />
      <input
        value={email}
        placeholder="Enter email"
        onChange={(e) => setEmail(e.target.value)}
      />
      <label>
        <input
          type="checkbox"
          checked={isSubscribed}
          onChange={(e) => setIsSubscribed(e.target.checked)}
        />
        Subscribe to updates
      </label>
      <p>Name: {name}</p>
      <p>Email: {email}</p>
      <p>Subscribed: {isSubscribed ? 'Yes' : 'No'}</p>
    </div>
  );
}
export default RegistrationForm;

Each state variable has its own initial value and setter function. This makes the component easier to understand and maintain.


10. Initializing State for Form Inputs

Forms commonly initialize text fields with empty strings, checkboxes with booleans, and selection fields with a suitable default option.

import { useState } from 'react';
function LoginForm() {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  return (
    <form onSubmit={(e) => e.preventDefault()}>
      <input
        type="email"
        value={email}
        placeholder="Email"
        onChange={(e) => setEmail(e.target.value)}
      />
      <input
        type="password"
        value={password}
        placeholder="Password"
        onChange={(e) => setPassword(e.target.value)}
      />
      <button type="submit">Log In</button>
    </form>
  );
}
export default LoginForm;

Both input fields begin as empty strings. Their displayed values are controlled by React state.


11. Initializing State vs Updating State

Initializing State Updating State
Sets the starting value on the first render. Requests a change to the current value.
Uses the initial argument of useState(). Uses the setter function returned by useState().
Example: useState(0) Example: setCount(1)
Does not automatically run again on every render. Can trigger a re-render when the next state differs.

12. Initializing State vs Regular Variables

A regular variable is recreated when the component function runs and does not independently trigger a render when changed. State is retained by React between renders and can trigger a render when updated.

function Example() {
  let count = 0;
  count = count + 1;
  return <p>Count: {count}</p>;
}

The regular variable does not preserve its value across renders. For values that need to persist and update the interface, use state.

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

13. Common Mistakes When Initializing State

Mistake 1: Calling a Hook conditionally

// Incorrect
if (isLoggedIn) {
  const [message, setMessage] = useState('');
}

Correct: Call Hooks at the top level of a function component or custom Hook, not inside conditions, loops, or nested functions.

const [message, setMessage] = useState('');
if (isLoggedIn) {
  // Use message here.
}

Mistake 2: Calling an initializer function unnecessarily

// May perform the calculation on every render
const [items, setItems] = useState(createInitialItems());

Better for an expensive initial calculation:

const [items, setItems] = useState(createInitialItems);

Mistake 3: Expecting the initial value to reset state

Changing the argument passed to useState() does not automatically reset an already initialized state variable. Use an explicit state update or a component key when a reset is required.

Mistake 4: Mutating an object or array

// Incorrect
user.name = 'Neha';
setUser(user);

Correct: Create a new object when updating object state.

setUser({ ...user, name: 'Neha' });

Mistake 5: Using an unsuitable initial value

Choose an initial value that matches the expected data type and usage. For example, use [] for a list, '' for a controlled text input, and false for a Boolean toggle.


14. Rules for Initializing State

  • Import useState from React when using the named Hook.
  • Call useState() at the top level of the component or custom Hook.
  • Choose a meaningful initial value.
  • Use descriptive names such as count, setCount, name, and setName.
  • Use lazy initialization when calculating the initial value is expensive.
  • Keep initializer functions pure and free of side effects.
  • Use the setter function to request state changes.
  • Replace objects and arrays rather than mutating them directly.
  • Remember that the initial argument is ignored after the first render.
  • Do not store redundant state when a value can be calculated from existing props or state.

15. Practical Example: Student Profile

This example demonstrates initializing a string, number, and Boolean in one React component.

import { useState } from 'react';
function StudentProfile() {
  const [studentName, setStudentName] = useState('Anjali');
  const [marks, setMarks] = useState(75);
  const [isPassed, setIsPassed] = useState(true);
  return (
    <div>
      <h2>Student Profile</h2>
      <p>Name: {studentName}</p>
      <p>Marks: {marks}</p>
      <p>Result: {isPassed ? 'Passed' : 'Not Passed'}</p>
      <button onClick={() => setStudentName('Riya')}>
        Change Name
      </button>
      <button onClick={() => setMarks(85)}>
        Update Marks
      </button>
      <button onClick={() => setIsPassed(!isPassed)}>
        Toggle Result
      </button>
    </div>
  );
}
export default StudentProfile;

Expected Behavior

  • The initial student name is Anjali.
  • The initial marks are 75.
  • The initial result is Passed.
  • Clicking the buttons updates the corresponding state value.
  • React renders the updated information on the screen.

16. Interview Questions and Answers

Q1. What is initializing state in React?

Initializing state means providing the starting value of a state variable when a component is first rendered.

Q2. Which Hook is commonly used to initialize state?

The useState() Hook is commonly used to initialize and manage state in functional components.

Q3. What is the syntax for initializing state?

const [state, setState] = useState(initialValue);

Q4. Which data types can be stored in state?

State can hold JavaScript values such as numbers, strings, booleans, arrays, objects, and null.

Q5. What happens if useState() is called without an argument?

The initial state is undefined.

Q6. What is lazy initialization?

Lazy initialization means passing a function to useState() so React can call it to calculate the initial state during initialization.

Q7. Does changing the initial value reset the current state?

No. React ignores the initial argument after the component's first render. An explicit update or a component reset may be needed.

Q8. Can a component have multiple state variables?

Yes. A component can call useState() multiple times to manage separate pieces of state.

Q9. Why should state objects not be mutated directly?

State should be treated as read-only. Create a new object or array and pass it to the setter to update the state correctly.

Q10. Where should useState() be called?

Call it at the top level of a function component or custom Hook, not inside loops, conditions, or nested functions.


17. Practice Exercises

  1. Create a counter initialized to 10 and add an Increase button.
  2. Create a text input initialized with an empty string and display the entered text.
  3. Create a Boolean state initialized to false to show or hide a message.
  4. Initialize an array with three programming languages and add a fourth language through a button.
  5. Initialize an object with a person's name and city, then update only the city.
  6. Create a student profile with name, marks, and result state variables.
  7. Create an initializer function that returns an array of default tasks and use lazy initialization.
  8. Initialize a form with empty email and password values.

18. Quick Revision Checklist

  • Understand the meaning of state and initial state.
  • Know the syntax and purpose of useState().
  • Initialize numbers, strings, booleans, arrays, and objects.
  • Understand lazy initialization.
  • Know how state initialized from props behaves.
  • Understand the difference between initializing and updating state.
  • Follow the Rules of Hooks.
  • Avoid directly mutating arrays and objects in state.
  • Practice examples involving counters, forms, and profile data.

19. Useful Resources


20. Conclusion

Initializing state is an important React concept because it defines the starting data used by a component. The useState() Hook supports simple initial values as well as arrays, objects, and lazy initializer functions. By choosing appropriate initial values, following the Rules of Hooks, and updating state without direct mutation, developers can build React interfaces that are easier to maintain and understand.

For structured learning, visit JustAcademy React JS Training Course or register for a React JS course demo.

whatsapp