createModule
The createModule
function enables you to create a module within your store. A module is a self-contained section of the state, allowing you to manage and update specific parts of the state independently. This approach is useful when you need to work with a specific part of the state without affecting the entire store.
Usage
Parameters
store
: The main store instance that holds the global state. This is passed as the first argument.moduleName
: The specific slice of the state that you want to manage. This corresponds to a key in the global state (e.g., “user” or “todos”).
Return Value
The createModule
function returns an object with the following methods:
getState()
: Returns the current state of the specified module.setState(updater)
: Updates the state of the specified module. The updater can either be a function that receives the current state of the module and returns a new state, or a partial object to merge with the existing module state.subscribe(listener)
: Subscribes a listener to the state changes of the specified module. The listener will only be called with changes related to the module.
Example
Creating and Using a Module