Skip to content

Instantly share code, notes, and snippets.

@luciaaldana
Last active September 27, 2022 14:40
Show Gist options
  • Save luciaaldana/d5445118263020994c33be1578144208 to your computer and use it in GitHub Desktop.
Save luciaaldana/d5445118263020994c33be1578144208 to your computer and use it in GitHub Desktop.
Config reduxjs/toolkit react-redux

React Redux & Redux Toolkit

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

Store.js

import { configureStore } from '@reduxjs/toolkit';
import authSlice from './auth/slice';

export const store = configureStore({
  reducer: {
    auth: authSlice,
  },
});

authSlice.js

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;

index.js

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>

);

How to use:

Docs React Redux: HOOKS

  • 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 }))
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment