Redux in React.js with Redux Toolkit

Pre-requisite:

  1. You must have basic concepts of React and have working knowlegde of it.

What is Redux?

When and why to use Redux?

Redux Toolkit

npx create-react-app redux
npm install react-redux redux @reduxjs/toolkit

What is CreateSlice

Reducers

const { createSlice } = require("@reduxjs/toolkit");const initialState = {
value: {}
}
export const userSlice = createSlice({
name: 'user',
initialState,
reducers: {
setUser: (state, action) =>{
console.log(action)
state.value = action.payload
}
}
})
export const { setUser } = userSlice.actionsexport default userSlice.reducer;
import { configureStore } from '@reduxjs/toolkit'import userReducer from './features/user/userSlice';export const store = configureStore({reducer: {user: userReducer}})
import React from 'react'import ReactDOM from 'react-dom'import './index.css'import App from './App'import { store } from './app/store'import { Provider } from 'react-redux'ReactDOM.render(<Provider store={store}><App /></Provider>,document.getElementById('root'))
function App() {return (<div className=""></div>);}export default App;
import { useDispatch, useSelector } from "react-redux";function App() {let user = useSelector(state=>state.user.value)return (<div className="">{user?.name}</div>);}export default App;
import { useEffect } from "react";import { useDispatch, useSelector } from "react-redux";import { setUser } from "./app/features/user/userSlice";function App() {let dispatch = useDispatch();let user = useSelector(state=>state.user.value)function newUser(){dispatch(setUser({ name: 'Musab Abbasi'}))}return (<div className="">{user?.name}<br /><button onClick={()=>newUser()}>Set User</button></div>);}export default App;

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Musab Abbasi

Musab Abbasi

88 Followers

Computer Science Graduate with MERN stack website development expertise.