MIT Weblab笔记 - React State Management
React Context
Previously, we pass state and setState as props through components to allow child component to update states of parent. If the component that needs the state is deep in the tree, this is a problem called “prop drilling”, where props are passed through many intermediate components.
The useState hook is commonly used to manage local component state. By combining it with Context, we can create a shared state accessible by any component in the tree. It’s particularly useful for global states, such as user authentication status, themes, or other application-wide settings.
- Create a Context
import React, { createContext, useState, useContext } from 'react';
const MyContext = createContext();
- Create a Provider: Can use context MyContext in any descendant of
MyContext.Provider.
const MyProvider = ({ children }) => {
const [state, setState] = useState(initialState);
return (
<MyContext.Provider value={{ state, setState }}>
{children}
</MyContext.Provider>
);
};
- Wrap Your Application: Make
MyComponenta descendent ofMyProvider, soMyComponentcan use the context.
const App = () => {
return (
<MyProvider>
<MyComponent />
</MyProvider>
);
};- Consume the Context: use
const { state, setState } = useContext(MyContext)to extract the value provided byMyContext.Provider.
const MyComponent = () => {
const { state, setState } = useContext(MyContext);
const handleChange = () => {
setState(newState);
};
return (
<div>
<p>{state.someValue}</p>
<button onClick={handleChange}>Change State</button>
</div>
);
};Reducers
Reducers provide a structured way to manage state transitions, especially for complex state logic or multiple state updates based on different actions.
const [state, dispatch] = useReducer(reducer, initialState)- Redcer: A function that specifies how the state should be updated based on the action.
Reducer: f(state, action) -> newState. The reducer function takes the current state and an action as arguments and returns a new state. The reducer returns a new state object. - Dispatch: Use the
dispatchfunction to trigger state transitions based on actions.
import React, { useReducer } from 'react';
const initialState = { count: 0 };
function reducer(state, action) {
switch (action.type) {
case 'increment':
return { count: state.count + 1 };
case 'decrement':
return { count: state.count - 1 };
default:
return state;
}
}
const Counter = () => {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<div>
<p>Count: {state.count}</p>
<button onClick={() => dispatch({ type: 'increment' })}>Increment</button>
<button onClick={() => dispatch({ type: 'decrement' })}>Decrement</button>
</div>
);
};
export default Counter;MIT Weblab笔记 - React State Management
http://example.com/2024/07/29/MIT_Weblab/React-State-Management/