Introduction to Reduck
Reduck is a powerful and versatile state management library designed to simplify the handling of application state in JavaScript. It provides a predictable state container for apps, enabling you to write applications that behave consistently and are easier to test.
Core APIs
createStore
The createStore
function initializes the application’s state store. It requires a reducer function and an initial state.
import { createStore } from 'reduck';
const initialState = { count: 0 };
function counterReducer(state = initialState, action) {
switch (action.type) {
case 'INCREMENT':
return { count: state.count + 1 };
case 'DECREMENT':
return { count: state.count - 1 };
default:
return state;
}
}
const store = createStore(counterReducer);
dispatch
The dispatch
method is used to send actions to change the state. It accepts an action object which describes the change.
store.dispatch({ type: 'INCREMENT' });
subscribe
The subscribe
method allows you to listen to state changes. It takes a listener function that will be called every time the state changes.
const unsubscribe = store.subscribe(() => {
console.log('State after dispatch: ', store.getState());
});
store.dispatch({ type: 'INCREMENT' }); // Remember to unsubscribe to prevent memory leaks unsubscribe();
combineReducers
The combineReducers
helper function turns an object whose values are different reducing functions into a single reducing function you can pass to createStore
.
import { combineReducers } from 'reduck';
const rootReducer = combineReducers({
counter: counterReducer,
// other reducers can be added here
});
const store = createStore(rootReducer);
App Example
Here’s a simple application example using Reduck to manage state for a counter app:
import React from 'react'; import { createStore } from 'reduck'; import { Provider, connect } from 'react-redux';
const initialState = { count: 0 };
function counterReducer(state = initialState, action) {
switch (action.type) {
case 'INCREMENT':
return { count: state.count + 1 };
case 'DECREMENT':
return { count: state.count - 1 };
default:
return state;
}
}
const store = createStore(counterReducer);
function App({ count, increment, decrement }) {
return (
Counter
{count}
);
}
const mapStateToProps = state => ({
count: state.count
});
const mapDispatchToProps = dispatch => ({
increment: () => dispatch({ type: 'INCREMENT' }),
decrement: () => dispatch({ type: 'DECREMENT' })
});
const ConnectedApp = connect(mapStateToProps, mapDispatchToProps)(App);
function Root() {
return (
);
}
export default Root;
Hash: 97c09be794e11ff8856f5c24d7bad406d949a4cd15626ea9395fc24359776f7f