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
1 |
|
- Create a Provider: Can use context MyContext in any descendant of
MyContext.Provider
.
1 |
|
- Wrap Your Application: Make
MyComponent
a descendent ofMyProvider
, soMyComponent
can use the context.
1 |
|
- Consume the Context: use
const { state, setState } = useContext(MyContext)
to extract the value provided byMyContext.Provider
.
1 |
|
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
dispatch
function to trigger state transitions based on actions.
1 |
|
MIT Weblab笔记 - React State Management
https://thiefcat.github.io/2024/07/29/MIT-Weblab/React-State-Management/