Redux is a state management library, that keeps the state available application wide.
see the code of Redux without reactjs below
also now CreateStore is deprecated.
Redux Program 1
keywords
reducer ->store -> subscribe -> dispatch -> action
run like a simple javascript file.
npm init
npm i redux
node mycode.js
const redux = require("redux");
const counterReducer = (state = { counter: 0 }, action) => {
if (action.type === "increment") {
return {
counter: state.counter + 1,
};
}
if (action.type === "decrement") {
return {
counter: state.counter - 1,
};
}
if (action.type === "multi5") {
return {
counter: state.counter * 5,
};
}
};
const store = redux.createStore(counterReducer);
const counterSubscriber = () => {
console.log(store.getState());
};
store.subscribe(counterSubscriber);
store.dispatch({ type: "increment" });
store.dispatch({ type: "multi5" });
store.dispatch({ type: "decrement" });
redux-toolkit program 2
do
npm init
npm install @reduxjs/toolkit
node redux-toolkit.js
import pkg from "@reduxjs/toolkit";
const { configureStore } = pkg;
const initialState = { value: 0, myName: "Govind" };
function counterReducer(state = initialState, action) {
// Check to see if the reducer cares about this action
if (action.type === "counter/increment") {
// If so, make a copy of `state`
return {
...state,
// and update the copy with the new value
value: state.value + 1,
};
}
// otherwise return the existing state unchanged
return state;
}
const store = configureStore({ reducer: counterReducer });
console.log(store.getState());
store.dispatch({ type: "counter/increment" });
console.log(store.getState());
//We can call action creators to dispatch the required action
const increment = () => {
return {
type: "counter/increment",
};
};
store.dispatch(increment());
console.log(store.getState());
// {value: 2}
//Selectors
// Selectors are functions that know how to extract specific pieces of information from a store state value.
const selectCounterValue = (state) => state.value;
const currentValue = selectCounterValue(store.getState());
console.log(currentValue); //2
const selectMyName = (state) => state.myName;
const name = selectMyName(store.getState());
console.log(name);
Top comments (0)