State Management Best Practices
CIIT Training Institute | Learn how to organize React state, use Redux Toolkit effectively, and build maintainable applications.
1. Introduction to State Management Best Practices
State management is an important part of building React applications. As an application grows, different components may need access to the same data. Without a clear strategy, state updates can become difficult to understand, test, and maintain.
Good state management means choosing the appropriate place for each piece of data, keeping updates predictable, avoiding unnecessary complexity, and organizing related application logic.
Important Principle
Do not put every piece of state into Redux. Use local component state for local UI behavior, and use shared state management when multiple parts of the application need coordinated access to the same data.
Choosing the Right State Management Approach
Local State
useState()
Component-specific data
Shared State
Context or Redux
Data used across components
2. Keep State as Local as Possible
If a piece of state is needed by only one component, keep it inside that component. This makes the component easier to understand and avoids unnecessary global state.
Example: Local Input State
import { useState } from "react";
function StudentSearch() {
const [search, setSearch] = useState("");
return (
<div>
<input
type="text"
value={search}
onChange={(event) =>
setSearch(event.target.value)
}
placeholder="Search students"
/>
<p>Search: {search}</p>
</div>
);
}
export default StudentSearch;
The search value is used only by StudentSearch, so local state is sufficient. Redux is not required for this example.
3. Avoid Unnecessary Prop Drilling
Prop drilling occurs when data must pass through multiple intermediate components just to reach a deeply nested component. For simple component trees, props are perfectly appropriate. For deeply shared state, Context or Redux may be more suitable.
Example: Passing Props Through Components
function App() {
const studentName = "Samadhan";
return (
<Dashboard studentName={studentName} />
);
}
function Dashboard({ studentName }) {
return (
<StudentProfile studentName={studentName} />
);
}
function StudentProfile({ studentName }) {
return (
<h2>Student: {studentName}</h2>
);
}
This example is valid React. However, as the component tree becomes deeper, passing the same props through components that do not use them can make the code harder to maintain.
4. Use Redux Toolkit for Shared State
Redux Toolkit is the recommended approach for writing Redux applications. It provides configureStore() and createSlice() to reduce boilerplate and organize state update logic.
Example: Counter Slice
import { createSlice } from "@reduxjs/toolkit";
const counterSlice = createSlice({
name: "counter",
initialState: {
value: 0
},
reducers: {
increment: (state) => {
state.value += 1;
},
decrement: (state) => {
state.value -= 1;
},
reset: (state) => {
state.value = 0;
}
}
});
export const {
increment,
decrement,
reset
} = counterSlice.actions;
export default counterSlice.reducer;
The slice keeps related reducer logic and action creators together. This is easier to maintain than scattering related Redux logic across many files.
5. Keep Reducers Predictable
Reducers should calculate the next state based on the current state and the action. They should not directly perform API requests, manipulate the DOM, or depend on unpredictable external side effects.
Example: Reducer with Redux Toolkit
const counterSlice = createSlice({
name: "counter",
initialState: {
value: 0
},
reducers: {
incrementByAmount: (state, action) => {
state.value += action.payload;
}
}
});
Dispatching the Action
dispatch(incrementByAmount(5));
If the current counter value is 10, the resulting value is 15. The reducer uses the action payload to calculate the next state.
6. Use useSelector() and useDispatch() Correctly
useSelector() reads selected values from the Redux store. useDispatch() provides the dispatch function for sending actions. Use them inside React function components or custom hooks.
Example
import {
useSelector,
useDispatch
} from "react-redux";
import {
increment,
decrement
} from "./counterSlice";
function Counter() {
const count = useSelector(
(state) => state.counter.value
);
const dispatch = useDispatch();
return (
<div>
<h2>Count: {count}</h2>
<button onClick={() =>
dispatch(increment())
}>
Increment
</button>
<button onClick={() =>
dispatch(decrement())
}>
Decrement
</button>
</div>
);
}
export default Counter;
7. Handle Loading, Success, and Error States
API requests can take time and may fail. A good application should clearly represent the request status instead of showing an empty screen or leaving users uncertain.
Example State Structure
const initialState = {
data: [],
loading: false,
error: null
};
Render the Appropriate UI
if (loading) {
return <p>Loading data...</p>;
}
if (error) {
return <p>Error: {error}</p>;
}
return (
<ul>
{data.map((student) => (
<li key={student.id}>
{student.name}
</li>
))}
</ul>
);
Request State Flow
Success
Display the data
Error
Display an error message
8. Avoid Unnecessary State
Do not store values in state if they can be calculated from existing props or state. Duplicating the same information can cause values to become inconsistent.
Less Maintainable Approach
const [price, setPrice] = useState(100);
const [quantity, setQuantity] = useState(2);
const [total, setTotal] = useState(200);
Here, total duplicates information that can be calculated from price and quantity.
Recommended Approach
const [price, setPrice] = useState(100);
const [quantity, setQuantity] = useState(2);
const total = price * quantity;
The total is calculated from the current values, so it does not need its own state variable.
9. Keep State Updates Immutable
In React, state should be updated according to the rules of the state management tool being used. With useState(), avoid mutating existing arrays or objects directly. With Redux Toolkit createSlice(), mutation-like syntax is supported because Immer creates the immutable updates.
React useState() Example
import { useState } from "react";
function StudentList() {
const [students, setStudents] = useState([
"Samadhan",
"Samiksha"
]);
function addStudent() {
setStudents((previousStudents) => [
...previousStudents,
"Prerna"
]);
}
return (
<div>
<button onClick={addStudent}>
Add Student
</button>
{students.map((student) => (
<p key={student}>{student}</p>
))}
</div>
);
}
export default StudentList;
10. Organize the Project Properly
A clear folder structure helps developers find related files, maintain features, and understand how state is managed.
Example Folder Structure
src/
|
|-- app/
| |-- store.js
|
|-- features/
| |-- counter/
| | |-- counterSlice.js
| | |-- Counter.jsx
| |
| |-- students/
| |-- studentSlice.js
| |-- StudentList.jsx
|
|-- App.jsx
|-- main.jsx
In this structure, store configuration is kept in the app folder, while each feature contains its related slice and components. Import paths should match the actual folder structure.
11. Common Mistakes to Avoid
Putting Everything in Redux
Not every input value, modal state, or temporary UI value needs to be stored globally.
Duplicating Derived Data
Calculate values from existing state whenever practical instead of maintaining unnecessary duplicate state.
Performing Side Effects in Reducers
Keep reducers focused on state updates. Use thunks or appropriate asynchronous tools for API requests.
Ignoring API Errors
Always consider loading, successful response, and failure states when building API-driven interfaces.
Using Incorrect Selector Paths
Make sure the path in useSelector() matches the reducers registered in configureStore().
12. Practice Tasks
Task 1: Local State
Create a search input using useState() and display the current search text.
Task 2: Redux Counter
Create a counter slice with increment, decrement, and reset actions, and connect it to a React component.
Task 3: Derived State
Create price and quantity state variables and calculate the total without storing it separately.
Task 4: API States
Fetch student data and display loading, success, and error states.
Task 5: Project Structure
Organize a React project into app, features, and component files with clear imports.
Summary
Effective state management begins by choosing the correct place for each piece of data. Local state is suitable for component-specific UI behavior, while Context or Redux can help manage shared state. Redux Toolkit provides organized slices and predictable state updates. Components can use useSelector() and useDispatch() to interact with Redux, while asynchronous operations should account for loading, success, and error states. Avoid unnecessary state, keep reducers predictable, and organize related files clearly. These practices help make React applications easier to maintain, debug, and extend.