리μ‘νΈμμ λͺ¨λ μνλ₯Ό μ μ μνλ‘ μ¬μ©νλ λ°©λ²
λͺ¨λ μν(module state) μ΄ν΄λ³΄κΈ°
λͺ¨λ μνλ λͺ¨λ μμ€μμ μ μλ λ³μλ€. ν¨μ μΈλΆμμ μ μλ λ³μλ₯Ό λͺ¨λ μνλΌκ³ κ°μ νκ³ μμ μ½λλ₯Ό μ΄ν΄λ³΄μ.
let state = {
count: 0;
}
ν΄λΉ κ°μ²΄κ° λͺ¨λ μνλΌκ³ ν λ, κ°μ²΄μ μ κ·Όνκ³ μνλ₯Ό λ³κ²½νλ ν¨μλ₯Ό μ μν΄λ³΄μ.
export const getState = () => state
export const setState = (newState) => {
state = newState
}
ν¨μλ₯Ό μ¬μ©ν΄ μνλ₯Ό κ°±μ ν μ μκ² setStateλ₯Ό μμ ν μ μλ€.
export const setState = (newState) => {
state = typeof nextState === 'function' ? newState(state) : newState
setState((state) => {
return {
...state,
count: state.count + 1
}
})
}
λͺ¨λ μνλ₯Ό μ§μ μ μνμ§ μκ³ , μνμ μνμ μ κ·Όν μ μλ ν¨μκ° λ΄λΆμ μλ 컨ν
μ΄λλ₯Ό λ§λ€ μ μλ€.
export const createContainer = (initialState) =>
{
let state = initialState
const getState = () => state
const setState = (newState) => {
state = typeof newState === 'function' ? newState(state) : newState
}
return { getState, setState }
}
컨ν
μ΄λλ λ€μκ³Ό κ°μ΄ μ¬μ©ν μ μλ€.
const { getState, setState } = createContainer({ count: 0 })
리μ‘νΈμμ λͺ¨λ μν μ¬μ©νκΈ°
ꡬλ
μΌλ‘ λͺ¨λ μν ꡬννλ μμ
type Store<T> = {
getState: () => T;
setState: (action: T | ((prev: T) => T)) => void;
subscribe: (callback: () => void) => void;
}
const createStore = <T extends unknown>(
initialState: T
): Store<T> => {
let state = initialState
const callbacks = new Set<() => void>();
const getState = () => state
const setState = (nextState: T | ((prev: T) => T))=> {
state = typeof nextState === 'function' ? (nextState as (prev: T) => T)(state) : nextState;
callbacks.forEach((callback) => callback())
}
const subscribe = (callback: () => void) => {
callbacks.add(callback)
return () => {
callbacks.delete(callback)
}
}
return { getState, setState, subscribe}
}
createStore μ¬μ©νκΈ°
import { createStore } from './store'
const store = createStore({ count: 0 })
store.setState({ count: 1})
store.subscribe(...)
storeμ μν κ°κ³Ό κ°±μ ν¨μλ₯Ό ννλ‘ λ°ννλ μ¬μ©μ μ μ ν
μ λ§λ€ μ μλ€.
const useStore = (store) => {
const [state, setState] = useState(store.getState());
useEffect(() => {
const unsubscribe = store.subscribe(() => {
setState(store.getState())
});
setState(store.getState())
return unsubscribe
}. [store])
return [state, store.setState]
}
useStore μ¬μ©νκΈ°
const [state, setState] = useStore(store)
const inc = () => {
setState((prev) => ({
...prev,
count: prev.count + 1
}))
}
return (
<div>
<h1>{state.count}</h1>
<button onClick={inc}>Increment</button>
</div>
)
Last updated