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.

  1. Create a Context
1
2
import React, { createContext, useState, useContext } from 'react';
const MyContext = createContext();
  1. Create a Provider: Can use context MyContext in any descendant of MyContext.Provider.
1
2
3
4
5
6
7
8
9
const MyProvider = ({ children }) => {
const [state, setState] = useState(initialState);

return (
<MyContext.Provider value={{ state, setState }}>
{children}
</MyContext.Provider>
);
};
  1. Wrap Your Application: Make MyComponent a descendent of MyProvider, so MyComponent can use the context.
1
2
3
4
5
6
7
const App = () => {
return (
<MyProvider>
<MyComponent />
</MyProvider>
);
};
  1. Consume the Context: use const { state, setState } = useContext(MyContext) to extract the value provided by MyContext.Provider.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
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 dispatch function to trigger state transitions based on actions.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
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
https://thiefcat.github.io/2024/07/29/MIT-Weblab/React-State-Management/
Author
小贼猫
Posted on
July 29, 2024
Licensed under