A global store is essential for app when the work base is dramatically growing, or it working a static environment. For vuejs Vuex store fill the gap. For react everybody talk about Reudx.
Redux little bit complicated,reducers,actions,state,store, lots of thing has to be managed. Redux also have another tool called redux-toolkit which is a helper class for managing redux store.
So where to start ?
As the first step install the basic dependencies and react base project (I skip the react part and leave it for you).
# Yarn
yarn add @reduxjs/toolkit
Folder and files needed
Redux didn’t bother about the folder structure of the store, create a folder redux and inside the folder, create store.js and sliceFile.js
Slice
createSlice method of redux-toolkit will automatically create actions and export state for us. Let’s configure reducer, which is the basic functions and a global state for the store. So let’s create the slice
import { createSlice } from "@reduxjs/toolkit"
export const hitSlice = createSlice({
name: "hit",
initialState: {
hitCount: 0,
isWorking: true
},
reducers: {
setHitCount: (state, action) => {
state.hitCount=action.payload
)
}
},
extraReducers: builder => {
}
}
)
export default hitSlice.reducer
So in our slice we had a hitCount state and reducer to set the hits, that’s all.
Configure the Store
Lets import the reducer from the slice we just made, a minimum setup is required.
//redux/store.js
import { configureStore } from "@reduxjs/toolkit";
import hitReducer from "./hitCounter";
export default configureStore({
reducer: { hits: hitReducer,
},
});
Our store just finished, and note that we didn’t export the state. In the index.js (in the root of the project) file we have to configure the redux provider and store, so that state will be available for all the components.
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import store from './redux/store';
import {Provider} from 'react-redux'
ReactDOM.render(
<React.StrictMode>
<Provider store={store}>
<App />
</Provider>
</React.StrictMode>,
document.getElementById('root')
);
Accessing the state
In the components we can access the with useSelector hook as follows
import { useSelector} from 'react-redux'
...
const {hits} = useSelector(state =>state.hits);
Accessing reducers/methods
Remember the setHitCount method we created , we have to use useDispatch hook to invoke the reducer function.
import { useDispatch } from 'react-redux'
import {setHitCounter} from './redux/hitCounter'
..
const dispatch = useDispatch();
dispatch(setHitCounter(3))
const {hits} = useSelector(state =>state.hits);
The hits is reactive in nature, when ever we change the state, all the app components will also get updated.
Async Call
It’s is often require that asynchronously fetching data from an API, redux can perform this using createThunk function. I saved the topic for next post