Managing State in a React Application
State management is a critical part of building a React application. It determines how data flows and how the application responds to user interactions.
Local State
Local state is managed within individual components using hooks like useState
and useReducer
. This method is simple and effective for small components.
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
export default Counter;
Global State Management
For managing global state, developers can use tools like Redux, Context API, or MobX. Redux offers a centralized store, making it easier to manage state changes throughout the application.
// Example of a simple Redux setup
import { createStore } from 'redux';
const initialState = { count: 0 };
function reducer(state = initialState, action) {
switch (action.type) {
case 'INCREMENT':
return { count: state.count + 1 };
default:
return state;
}
}
const store = createStore(reducer);
export default store;
Leave a Reply