Redux is a powerful state management tool for JavaScript applications, allowing developers to manage and maintain application state in a predictable and efficient manner. In this blog, we will go over the steps to set up Redux in a vanilla JavaScript application.
First we will generate a vanilla js project using vite.
Getting Started
First, we need to install the Redux library. We can do this by running the following command in our terminal:
npm install redux --save
Next, we need to create a store for our application state. The store is the central location where all of our application data is stored and managed. We can create a store by importing the createStore method from the Redux library and passing it our reducer function.
Create a file with name store.js
and add following code in it.
import { createStore } from "redux"
export const store = createStore(reducer)
The reducer function is responsible for updating the state based on the action that is dispatched. It is a pure function that takes in the current state and an action, and returns the next state.
Create a file with name reducer.js
and add following code.
export const reducer = (state, action) => {
switch (action.type) {
case "ADD_ITEM":
return {
...state,
items: [...state.items, action.item],
}
default:
return state
}
}
Import this reducer function in store.js
file.
Now that we have our store and reducer set up, we can start dispatching actions to update the state. We can dispatch an action by calling the dispatch method on the store, passing in the action object.
Import store
from store.js
in index.js file and add following code.
store.dispatch({
type: "ADD_ITEM",
item: {
id: 1,
name: "item1",
},
})
We can also subscribe to the store to be notified of any state changes. This is useful for updating our UI whenever the state is updated. We can subscribe by calling the subscribe
method on the store and passing in a callback function.
store.subscribe(() => {
console.log(store.getState())
})
Finally, we can access the current state of the store by calling the getState
method on the store. This is useful for getting the current state to render in our UI or for performing calculations.
const currentState = store.getState()
Top comments (0)