Redux: Vanilla JavaScript
Though redux have lots of features, you can read about all of them here but main feature because of which everyone is using Redux is that it can be very useful to manage state of the application at global level.
It can be used with any JavaScript or TypeScript code. It keeps our state container centralized and predictable for our JavaScript Apps.
Side Effect: Redux is synchronous by nature and if you want to make async call requests like an API call, redux need additional middlewares. Some of the popular middleware are Redux Thunk and Redux Saga.
Lets try to setup redux with plain vanilla javascript for better understanding.
First thing you need is a library. To download the redux library you can use NPM or Yarn.
npm install redux
or
yarn add redux
Now redux based application needs a Reducer. It contains code to handle action which is being performed and change the state according to the action.
const myReducer = (state, action) => {
if(action.type === "ADD"){
//change state
}
}
Next comes Store, it is as name suggest it stores the state and bind everything together at one place. To initialize the store, reducer need to be pass as parameter. Store can have multiple reducers.
const store = createStore(myReducer,
window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__ //to make the redux tool (chrome) working
)
Next step is to trigger the action, in redux terminology it is Dispatch
const myAction = {type: "ADD", payload: "1"}
store.dispatch(myAction)
Now you need subscriber for the dispatch, section which will trigger if dipatch is called.
store.subscribe(() ->{
console.log(store.getState());
})
Your basic redux flow on plain JavaScript is ready.
Comment us below, to share your experience.
Related Posts
StacKnowledge
To handle asynchronous operations – such as making API calls – it requires the use of middleware. Learn more about it – https://stacknowledge.in/blogs/redux-saga-thunk-middleware/



2 comments