Introduction
Greetings, CSharpCorner readers! Today, let's dive deep into the intricate world of state management in React. As a React enthusiast, you're likely aware that choosing the right state management technique can significantly impact your application's structure and performance. In this blog post, we'll explore various state management techniques, ranging from local state and Context API to powerful libraries like Redux, MobX, and even the useReducer hook. Additionally, we'll touch upon the Yup library for handling form validation seamlessly.
1. Local State. The Foundation
We kick off our journey with the fundamental concept of local state using the useState hook. Perfect for managing states within individual components, this technique is lightweight and ideal for simpler scenarios.
import React, { useState } from 'react';
function CounterComponent() {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
2. Context API. Bridging Components Seamlessly
When prop drilling becomes cumbersome, the Context API comes to the rescue. Share state across multiple components effortlessly with createContext and useContext.
import React, { createContext, useContext, useState } from 'react';
const MyContext = createContext();
function MyProvider({ children }) {
const [value, setValue] = useState('Default Value');
return (
<MyContext.Provider value={{ value, setValue }}>
{children}
</MyContext.Provider>
);
}
function ChildComponent() {
const { value, setValue } = useContext(MyContext);
return (
<div>
<p>Value: {value}</p>
<button onClick={() => setValue('New Value')}>Change Value</button>
</div>
);
}
3. Redux. Centralized and Predictable State Management
For larger applications, Redux remains a stalwart choice. Predictable state management, actions, and reducers combine to form a robust solution.
// actions.js
export const increment = () => ({ type: 'INCREMENT' });
// reducers.js
const counterReducer = (state = 0, action) => {
switch (action.type) {
case 'INCREMENT':
return state + 1;
default:
return state;
}
};
// store.js
import { createStore } from 'redux';
import counterReducer from './reducers';
const store = createStore(counterReducer);
// App.js
import React from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { increment } from './actions';
function App() {
const count = useSelector((state) => state);
const dispatch = useDispatch();
return (
<div>
<p>Count: {count}</p>
<button onClick={() => dispatch(increment())}>Increment</button>
</div>
);
}

Join the conversation! Your thoughts help the community grow.