06. Introduction to Global State Management Libraries
π 1. Two Problems in Global State Design
(1) How to Read Global State
(2) How to Put or Update Values in Global State
Example Code Solving Both Problems
// Store implementation for managing global state
const createStore = (initialState) => {
let state = initialState;
const listeners = new Set();
// Function to read global state
const getState = () => state;
// Function to update global state
const setState = (newState) => {
//
state = { ...state, ...newState };
// Notify registered listeners (subscribers) when state changes
listeners.forEach((listener) => listener());
};
const subscribe = (listener) => {
listeners.add(listener);
return () => listeners.delete(listener);
};
return { getState, setState, subscribe };
};
// Initial global state: user is a nested object
const store = createStore({
user: {
name: 'Ella',
age: 20,
},
theme: 'dark',
});
// Provide dedicated function for global state changes
function setUserName(newName) {
// Update user object in global state while maintaining immutability
const current = store.getState();
store.setState({
user: {
...current.user,
name: newName,
},
});
}
// Usage example: change user.name using dedicated function instead of directly
setUserName('Chloe');
console.log(store.getState().user.name); // "Chloe"π 2. Using Data-Centric and Component-Centric Approaches
Data-Centric Approach
Component-Centric Approach
Factory Function
Factory Function? Factory Pattern?
Component-Centric Approach Example Code
π 3. Re-rendering Optimization
Using Selector Functions
State Usage Tracking
State Usage Tracking vs. Subscription
Using Atoms
My Thoughts
Code Examples
Previous05. Sharing Component State with Context and SubscriptionsNext07. Use Case Scenario 1: Zustand
Last updated