Initializing State in React JS
Topic: Initializing State in React
Technology: React JS, JavaScript, JSX, Functional Components, useState Hook
Learning Objective: Understand how to initialize state in React components, choose appropriate initial values, initialize different data types, use lazy initialization for expensive calculations, and apply state initialization in practical React applications.
1. Introduction to Initializing State
Initializing state means assigning a starting value to a state variable when a React component is initialized. React components often need to remember information such as a counter value, a user's name, a form field, a selected tab, or a list of tasks. Initial state provides the value that the component uses when it first renders.
In functional components, state is commonly initialized using the built-in React useState Hook. React remembers the state between renders and provides the current value whenever the component renders again.
For example, a counter can begin at zero, a text field can begin with an empty string, and a menu visibility state can begin with false.
Basic Example
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<h2>Count: {count}</h2>
<button onClick={() => setCount(count + 1)}>
Increase Count
</button>
</div>
);
}
export default Counter;
Explanation: The state variable count is initialized to 0. React displays this value during the initial render. When the button is clicked, setCount requests an update to the state.
2. What Is State in React?
State is component-specific information that React preserves between renders. When state changes, React can render the component again to display the updated information.
Examples of state in React applications
- Counter: Stores the current number.
- Login form: Stores the entered email and password fields.
- Shopping cart: Stores selected products and quantities.
- Navigation menu: Stores whether the menu is open or closed.
- To-do application: Stores a list of tasks.
- Product page: Stores the selected size, color, or quantity.
- Theme selector: Stores whether the user selected light or dark mode.
Why is state initialization important?
Initializing state gives a component a predictable starting point. Without an appropriate initial value, the component may not have the information needed to display the expected interface. Choosing a suitable initial value also helps avoid errors when rendering data or handling user interactions.
3. Syntax for Initializing State
The standard syntax for initializing state using the useState Hook is:
const [state, setState] = useState(initialValue);
Understanding the syntax
useState: React Hook used to declare a state variable.
initialValue: The value React uses when initializing the state.
state: The current state value for the current render.
setState: The function used to request a state update.
const: Declares the local variable bindings returned through array destructuring.
Example
import { useState } from 'react';
function UserGreeting() {
const [name, setName] = useState('Guest');
return (
<div>
<h2>Welcome, {name}!</h2>
<button onClick={() => setName('Manish')}>
Update Name
</button>
</div>
);
}
export default UserGreeting;
Initially, the name is set to 'Guest'. After clicking the button, React updates the name to 'Manish' and renders the updated greeting.
4. Initializing State with Different Data Types
The useState Hook can initialize state with different JavaScript values. Select the initial value based on the information the component needs to store.
4.1 Initializing Number State
Number state is useful for counters, scores, product quantities, page numbers, and ratings.
import { useState } from 'react';
function ScoreCounter() {
const [score, setScore] = useState(0);
return (
<div>
<h2>Score: {score}</h2>
<button onClick={() => setScore(score + 1)}>
Add Score
</button>
</div>
);
}
export default ScoreCounter;
Initial value: 0
The score begins at zero and increases when the user clicks the button.
4.2 Initializing String State
String state is used for text values such as names, messages, search queries, and form fields.
import { useState } from 'react';
function NameDisplay() {
const [name, setName] = useState('');
return (
<div>
<input
value={name}
onChange={event => setName(event.target.value)}
placeholder="Enter your name"
/>
<p>Your name: {name || 'Not entered'}</p>
</div>
);
}
export default NameDisplay;
Initial value: '', which is an empty string. This is a common initial value for a controlled text input.
4.3 Initializing Boolean State
Boolean state stores either true or false. It is commonly used for toggles, visibility, checkboxes, and status indicators.
import { useState } from 'react';
function VisibilityToggle() {
const [isVisible, setIsVisible] = useState(false);
return (
<div>
<button onClick={() => setIsVisible(previous => !previous)}>
Toggle Message
</button>
{isVisible && <p>Welcome to React JS!</p>}
</div>
);
}
export default VisibilityToggle;
Initial value: false. The message is initially hidden and appears when the state becomes true.
4.4 Initializing Array State
Array state is useful for lists of tasks, products, names, categories, and notifications.
import { useState } from 'react';
function FruitList() {
const [fruits, setFruits] = useState(['Apple', 'Banana']);
return (
<div>
<h2>Fruits</h2>
<ul>
{fruits.map((fruit, index) => (
<li key={`${fruit}-${index}`}>{fruit}</li>
))}
</ul>
<button onClick={() =>
setFruits(previous => [...previous, 'Mango'])
}>
Add Mango
</button>
</div>
);
}
export default FruitList;
Initial value: An array containing 'Apple' and 'Banana'. The button adds another item by creating a new array.
4.5 Initializing Object State
Object state is useful for storing related values such as a user's name, email, address, or profile details.
import { useState } from 'react';
function UserProfile() {
const [user, setUser] = useState({
name: 'Amit',
city: 'Mumbai',
age: 25
});
return (
<div>
<h2>User Profile</h2>
<p>Name: {user.name}</p>
<p>City: {user.city}</p>
<p>Age: {user.age}</p>
<button onClick={() =>
setUser(previous => ({
...previous,
city: 'Pune'
}))
}>
Change City
</button>
</div>
);
}
export default UserProfile;
Initial value: An object containing the user's name, city, and age. When updating the city, the spread operator preserves the other properties.
5. Initializing State with Empty Values
Sometimes a component does not have data available at the beginning. In such cases, you can initialize state with an empty value appropriate for the expected data type.
| Data Requirement |
Example Initial Value |
Common Use |
| Text |
'' |
Input field or search box |
| Number |
0 |
Counter or quantity |
| Boolean |
false |
Closed menu or unchecked option |
| Array |
[] |
Task list or product list |
| Object |
{} |
Empty collection of properties, when appropriate |
| Optional value |
null |
Unknown or not-yet-selected item |
Example: Empty task list
import { useState } from 'react';
function TaskList() {
const [tasks, setTasks] = useState([]);
return (
<div>
<h2>My Tasks</h2>
{tasks.length === 0 ? (
<p>No tasks available.</p>
) : (
<ul>
{tasks.map((task, index) => (
<li key={index}>{task}</li>
))}
</ul>
)}
</div>
);
}
export default TaskList;
Because the initial array is empty, the component displays “No tasks available.” until tasks are added.
6. Initializing Multiple State Variables
A component can initialize several independent state variables using multiple useState calls. Each Hook manages its own state value and setter function.
import { useState } from 'react';
function StudentDetails() {
const [name, setName] = useState('Aarav');
const [age, setAge] = useState(20);
const [course, setCourse] = useState('React JS');
const [isEnrolled, setIsEnrolled] = useState(true);
return (
<div>
<h2>Student Details</h2>
<p>Name: {name}</p>
<p>Age: {age}</p>
<p>Course: {course}</p>
<p>Enrolled: {isEnrolled ? 'Yes' : 'No'}</p>
<button onClick={() => setName('Riya')}>Change Name</button>
<button onClick={() => setAge(age + 1)}>Increase Age</button>
<button onClick={() => setCourse('JavaScript')}>Change Course</button>
<button onClick={() => setIsEnrolled(previous => !previous)}>
Toggle Enrollment
</button>
</div>
);
}
export default StudentDetails;
Each state variable starts with its own initial value. Updating one variable does not automatically change the others.
7. Initial State Is Used on the First Render
React uses the initial state when a component's state is initialized. On subsequent renders, React preserves the current state instead of resetting it to the original initial value.
Example
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(5);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>
Increase
</button>
</div>
);
}
export default Counter;
The initial count is 5. After clicking Increase, the count becomes 6. React does not reset the count to 5 on every render.
Important distinction
const [count, setCount] = useState(5);
The value 5 is the initial state, not a permanent value. The state can change through setCount, and React preserves the updated value across ordinary re-renders of the same component instance.
8. Initializing State with a Function
When the initial state requires a calculation, you can pass a function to useState. This technique is called lazy initialization. It is useful when calculating the initial value is expensive, such as preparing a large list or processing stored data.
Direct initialization
const [items, setItems] = useState(createInitialItems());
In this example, JavaScript calls createInitialItems() whenever the component function runs. React uses its returned value only when initializing the state, so the calculation may be repeated unnecessarily on later renders.
Lazy initialization
const [items, setItems] = useState(createInitialItems);
Here, the function itself is passed to useState. React calls it to obtain the initial state during initialization, rather than requiring the component to calculate that value on every render.
Complete example
import { useState } from 'react';
function createInitialItems() {
console.log('Creating initial items');
return ['Learn JSX', 'Learn Props', 'Learn State'];
}
function TodoList() {
const [items, setItems] = useState(createInitialItems);
return (
<div>
<h2>Learning Tasks</h2>
<ul>
{items.map((item, index) => (
<li key={item}>{item}</li>
))}
</ul>
<button onClick={() =>
setItems(previous => [...previous, 'Practice React'])
}>
Add Task
</button>
</div>
);
}
export default TodoList;
Note: Initializer functions should be pure, meaning they should calculate and return a value without performing side effects. React Strict Mode may call an initializer more than once in development to help detect accidental impurities.
9. Initializing State from Props
Sometimes a component receives an initial value through props. That value can be used to initialize local state.
import { useState } from 'react';
function Counter({ initialCount }) {
const [count, setCount] = useState(initialCount);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(previous => previous + 1)}>
Increase
</button>
</div>
);
}
export default Counter;
If the parent renders <Counter initialCount={10} />, the counter initializes to 10. After the component updates its own state, a later change to the initialCount prop does not automatically reset that state.
Important consideration
Use this pattern when the prop represents an initial or starting value. If the component must always display the latest prop value, use the prop directly instead of copying it into state. If you need to reset the component when a particular value changes, consider giving the component a different React key so React treats it as a new component instance.
10. Initializing State from Browser Storage
A React component can initialize state from browser storage when the application needs to restore a value previously saved in the browser. For example, a theme preference or a draft setting might be read from localStorage.
Example: Initializing a theme preference
import { useState } from 'react';
function ThemeSelector() {
const [theme, setTheme] = useState(() => {
const savedTheme = localStorage.getItem('theme');
return savedTheme ?? 'light';
});
function changeTheme() {
const nextTheme = theme === 'light' ? 'dark' : 'light';
setTheme(nextTheme);
localStorage.setItem('theme', nextTheme);
}
return (
<div>
<p>Current theme: {theme}</p>
<button onClick={changeTheme}>Change Theme</button>
</div>
);
}
export default ThemeSelector;
Explanation: The initializer reads the saved theme and falls back to 'light' if no value exists. Clicking the button changes the state and saves the new preference.
Important: This browser-only example assumes localStorage is available. In server-rendered applications, direct browser storage access during initialization can cause errors or differences between server and client rendering. In those cases, initialize with a compatible default and read browser storage in an appropriate client-side effect or framework-specific approach.
11. Initializing State for Controlled Form Inputs
Controlled form inputs use React state to determine their displayed values. Initializing the state with a suitable value helps ensure the input behaves consistently.
Text input example
import { useState } from 'react';
function LoginForm() {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
function handleSubmit(event) {
event.preventDefault();
alert(`Email entered: ${email}`);
}
return (
<form onSubmit={handleSubmit}>
<label htmlFor="email">Email:</label>
<input
id="email"
type="email"
value={email}
onChange={event => setEmail(event.target.value)}
/>
<label htmlFor="password">Password:</label>
<input
id="password"
type="password"
value={password}
onChange={event => setPassword(event.target.value)}
/>
<button type="submit">Submit</button>
</form>
);
}
export default LoginForm;
The email and password states are initialized with empty strings. As the user types, each input's change handler updates the corresponding state value.
Why are appropriate initial values important?
- Text inputs can consistently use string values.
- Checkboxes can use Boolean values.
- Select controls can use a suitable initial option or an empty string.
- Forms can display predictable values before the user enters information.
- Using the correct type helps prevent controlled and uncontrolled input warnings.
12. Initializing Checkbox and Toggle State
Checkboxes and toggle controls commonly use Boolean state. Decide whether the control should begin selected or unselected.
import { useState } from 'react';
function TermsCheckbox() {
const [accepted, setAccepted] = useState(false);
return (
<div>
<label>
<input
type="checkbox"
checked={accepted}
onChange={event => setAccepted(event.target.checked)}
/>
I accept the terms and conditions
</label>
<p>Status: {accepted ? 'Accepted' : 'Not accepted'}</p>
</div>
);
}
export default TermsCheckbox;
The initial value false means the checkbox starts unchecked. When the user changes the checkbox, React updates the Boolean state using event.target.checked.
13. Initializing State with Calculated Values
Sometimes the initial value can be derived from a calculation. Simple calculations can be passed directly to useState, but expensive calculations are usually better handled with a lazy initializer.
Simple initial calculation
const [total, setTotal] = useState(100 + 50);
The initial value of total is 150.
Expensive initial calculation
function calculateInitialTotal() {
let total = 0;
for (let i = 1; i <= 1000; i++) {
total += i;
}
return total;
}
const [total, setTotal] = useState(calculateInitialTotal);
The initializer function is used to calculate the starting total. It avoids recalculating that initial value every time the component re-renders.
Do not use state merely to store values that can be calculated cheaply from the current props or state during rendering. Unnecessary derived state can become inconsistent with its source values.
14. Initializing State with Null or Undefined
React can store null or undefined as state values, but the choice should reflect the intended meaning and the component's needs.
import { useState } from 'react';
function SelectedProduct() {
const [product, setProduct] = useState(null);
return (
<div>
{product === null ? (
<p>No product selected.</p>
) : (
<p>Selected product: {product.name}</p>
)}
<button onClick={() =>
setProduct({ name: 'Laptop' })
}>
Select Laptop
</button>
</div>
);
}
export default SelectedProduct;
The initial value null explicitly represents the absence of a selected product. The component checks for that state before trying to display the product's name.
For controlled text inputs, prefer an initial string such as '' rather than undefined or null, because the input should remain consistently controlled.
15. Common Mistakes in State Initialization
| Mistake |
Problem |
Correct Approach |
| Using the wrong data type |
Can lead to unexpected operations or rendering behavior. |
Choose a suitable initial value for the expected state. |
| Expecting initial state to reset on every render |
React preserves the current state for the same component instance. |
Use a setter to update state or intentionally reset the component. |
| Calling an expensive function directly in useState |
The function call can run on every component render. |
Pass the initializer function itself for lazy initialization. |
| Passing a function when intending to store it as a value |
React interprets a function argument as an initializer. |
Use useState(() => someFunction) to store a function value. |
| Copying props into state without a reason |
The local state can become outdated when props change. |
Use props directly unless the component needs an independent initial value. |
| Mutating initial objects or arrays later |
Can lead to state updates that React does not detect as expected. |
Use immutable updates that create new objects or arrays. |
| Reading browser storage in an incompatible environment |
Browser globals may not exist during server rendering. |
Use a client-compatible initialization strategy. |
| Calling useState inside a condition |
Violates the Rules of Hooks. |
Call Hooks at the top level of the component. |
16. Rules to Follow When Initializing State
- Call the useState Hook at the top level of a function component or custom Hook.
- Do not call Hooks inside loops, conditions, or nested functions.
- Choose an initial value that matches the data your component needs to manage.
- Remember that React uses the initial state during initialization and ignores that argument on subsequent renders.
- Use lazy initialization for expensive calculations when appropriate.
- Keep initializer functions pure and free of side effects.
- Treat objects and arrays in state as read-only.
- Use setter functions to update state.
- Do not expect a state setter to change the state variable immediately in the current render.
- Consider whether a value should be state at all, or whether it can be calculated from existing props and state.
17. Difference Between Initial State and Updated State
| Feature |
Initial State |
Updated State |
| Meaning |
The starting value used when state is initialized. |
A later value requested through the setter function. |
| Example |
useState(0) |
setCount(5) |
| When it is used |
During state initialization. |
When the component requests a state change. |
| Does it reset automatically? |
No. It is not reapplied on each render. |
React preserves the resulting state across normal re-renders. |
| Effect on UI |
Provides the starting data for the first render. |
Can cause the component to render with new data. |
18. Practical Project: Student Profile Initialization
Project Objective: Create a student profile component that initializes state for a name, course, and enrollment status. Allow the user to update the name and toggle enrollment.
Complete Code
import { useState } from 'react';
function StudentProfile() {
const [name, setName] = useState('Aarav');
const [course, setCourse] = useState('React JS');
const [isEnrolled, setIsEnrolled] = useState(true);
return (
<div>
<h1>Student Profile</h1>
<p>Name: {name}</p>
<p>Course: {course}</p>
<p>Enrollment: {isEnrolled ? 'Active' : 'Inactive'}</p>
<button onClick={() => setName('Riya')}>
Update Name
</button>
<button onClick={() => setCourse('JavaScript')}>
Change Course
</button>
<button onClick={() =>
setIsEnrolled(previous => !previous)
}>
Toggle Enrollment
</button>
</div>
);
}
export default StudentProfile;
Project Explanation
- The name starts as
'Aarav'.
- The course starts as
'React JS'.
- The enrollment status starts as
true.
- The Update Name button changes the name to Riya.
- The Change Course button updates the course.
- The Toggle Enrollment button switches between active and inactive status.
Expected Output
Student Profile
Name: Aarav
Course: React JS
Enrollment: Active
[Update Name] [Change Course] [Toggle Enrollment]
The initial values appear when the component first renders. Clicking the buttons requests state updates and displays the new values.
19. Practical Project: Initializing a To-Do List
Project Objective: Initialize an empty array for tasks, initialize an empty string for the input field, and add tasks to the list using state updates.
import { useState } from 'react';
function TodoApp() {
const [task, setTask] = useState('');
const [tasks, setTasks] = useState([]);
function addTask() {
const trimmedTask = task.trim();
if (trimmedTask === '') {
return;
}
setTasks(previousTasks => [
...previousTasks,
{
id: crypto.randomUUID(),
title: trimmedTask
}
]);
setTask('');
}
return (
<div>
<h1>My To-Do List</h1>
<input
value={task}
onChange={event => setTask(event.target.value)}
placeholder="Enter a task"
/>
<button onClick={addTask}>Add Task</button>
{tasks.length === 0 ? (
<p>No tasks added yet.</p>
) : (
<ul>
{tasks.map(item => (
<li key={item.id}>{item.title}</li>
))}
</ul>
)}
</div>
);
}
export default TodoApp;
This project uses '' to initialize the input value and [] to initialize the task list. It also demonstrates controlled inputs, conditional rendering, and immutable array updates. The example uses crypto.randomUUID(), which is available in supported modern browser environments.
20. Advantages of Correct State Initialization
- Provides predictable starting values for React components.
- Helps avoid errors caused by unexpected or missing values.
- Makes form fields and interactive controls easier to manage.
- Supports conditional rendering based on the initial state.
- Improves the readability and maintainability of component code.
- Allows the application to begin with useful default information.
- Lazy initialization can avoid repeating expensive initial calculations during re-renders.
- Helps developers reason about how a component changes from its initial display to later states.
21. Frequently Asked Interview Questions and Answers
Q1. What is initializing state in React?
Answer: Initializing state means assigning a starting value to a state variable when React initializes it in a component. The useState Hook is a common way to initialize state in function components.
Q2. How do you initialize state using useState?
Answer: Import useState and write const [count, setCount] = useState(0). The state starts at zero, and the setter function can request future updates.
Q3. Which data types can useState store?
Answer: It can store numbers, strings, Booleans, arrays, objects, null values, and other JavaScript values.
Q4. Does React use the initial value on every render?
Answer: No. React uses the initial value when initializing the state. On subsequent renders, it preserves and returns the current state.
Q5. What is lazy initialization?
Answer: Lazy initialization means passing an initializer function to useState so React can call it to calculate the starting value. It is useful when the initial calculation is expensive.
Q6. What is the difference between useState(createItems()) and useState(createItems)?
Answer: In the first example, createItems() is called while the component function runs, so the calculation can repeat on re-renders. In the second, the function itself is passed as an initializer, so React calls it when initializing the state.
Q7. Can state be initialized from props?
Answer: Yes. A prop can provide the initial value, such as useState(initialCount). However, changes to the prop do not automatically reset the local state.
Q8. Can state start with an empty array?
Answer: Yes. An empty array, [], is commonly used when a list starts with no items.
Q9. Can state start with null?
Answer: Yes. Null can represent a value that is currently absent, such as a product that has not been selected.
Q10. What happens if a function is passed as the initial state?
Answer: React treats the function as an initializer and calls it to obtain the initial state. To store a function itself as state, use a wrapper such as useState(() => someFunction).
Q11. Why should initializer functions be pure?
Answer: React may call an initializer more than once in development to detect accidental impurities. A pure initializer returns a result without modifying external data or performing side effects.
Q12. How do you initialize a controlled text input?
Answer: Initialize its state with an empty string, such as const [name, setName] = useState(''), then connect the input's value and onChange properties to that state.
22. Practice Exercises
- Create a counter initialized to zero and add Increase, Decrease, and Reset buttons.
- Create a greeting component with a name initialized to
'Guest'.
- Create a form with name and email fields initialized to empty strings.
- Create a Boolean state variable that controls whether a message is visible.
- Initialize an empty array and add new tasks using a button.
- Create an object state variable containing a student's name, course, and age.
- Write a lazy initializer that returns an array of default categories.
- Initialize a selected product with
null and display a message when no product is selected.
- Create a theme selector that starts in light mode.
- Explain why a prop used as an initial state does not automatically reset the state when the prop changes.
23. Quick Revision Checklist
- Understand the meaning of state initialization.
- Know the syntax of the useState Hook.
- Choose suitable initial values for numbers, strings, Booleans, arrays, and objects.
- Understand that React uses the initial state during initialization, not every render.
- Know when to use lazy initialization.
- Understand how props can provide an initial state value.
- Initialize controlled text inputs with strings and checkboxes with Booleans.
- Know how to represent missing data using values such as null.
- Avoid direct mutation of state objects and arrays.
- Follow the Rules of Hooks and keep initializer functions pure.
- Practice state initialization in counters, forms, profiles, and to-do applications.
24. Official React Documentation
Use the official React documentation to learn more about state initialization and the useState Hook:
25. React JS Training Course and Demo Registration
Explore the following JustAcademy resources to learn React JS concepts, practise component development, and build interactive frontend applications.
React JS Training Course: JustAcademy React JS Training Course
Course Demo Registration: Register for React JS Course Demo
Conclusion
Initializing state is an essential part of React development because it defines the starting data for a component. By using the useState Hook with appropriate initial values, developers can manage counters, forms, lists, profiles, toggles, and other interactive features. Understanding lazy initialization, initial state from props, browser storage considerations, and the difference between initial and updated state helps you build more predictable and maintainable React applications.
Practise the examples and exercises in these notes to strengthen your understanding of state initialization before moving on to more advanced React topics.