React Redux is the official React UI bindings layer for Redux. It lets your React components read data from a Redux store, and dispatch actions to the store to update state.
The Redux Toolkit package is intended to be the standard way to write Redux logic.
npm install @reduxjs/toolkit react-redux
import { configureStore } from '@reduxjs/toolkit';
import authSlice from './auth/slice';
export const store = configureStore({
reducer: {
auth: authSlice,
},
});
import { createSlice } from '@reduxjs/toolkit';
const initialState = {
// ...user info
isLoggin: false,
};
const authSlice = createSlice({
name: 'auth',
initialState,
reducers: {
onLogin: (state, action) => {
state.isLoggin = action.payload
}
}
});
export const { onLogin } = authSlice.actions;
export default authSlice.reducer;
import React from 'react';
import ReactDOM from 'react-dom/client';
import { Provider } from 'react-redux';
import { store } from './store'
import App from './App';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<Provider store={store}>
<App />
</Provider>
);
- useSelector: Allows you to extract data from the Redux store state, using a selector function.
import { useSelector } from 'react-redux';
const isLoggin = useSelector(state => state.auth.isLoggin);
console.log(isLoggin); // false
- useDispatch: This hook returns a reference to the dispatch function from the Redux store. You may use it to dispatch actions as needed.
import { useDispatch } from 'react-redux';
import { onLogin } from '../../store/authSlice';
const dispatch = useDispatch();
const someFunction= () => {
dispatch(onLogin({isLoggin: true }))
};