Search code examples
reactjsreact-redux

Get state value without using useSelector


Is there any way of getting the state value without using useSelector with using it in React Component

import { superAdmin, zoneManager } from './navigations'
import { useSelector } from 'react-redux'

const access = useSelector(state => state.access)
return access

The Error I get is:

Invalid hook call. Hooks can only be called inside of the body of a function component.

Which I get it but is there any other way of getting the store value without the use of useSelector

Thank You


Solution

  • To make the store accessible anywhere (for whatever reason), you first need to export the store from the file where you are making it:

    // fileThatMakesStore.js
    export const store = configureStore();
    

    Then, back in your file, you can simply import the store and getState().

    import { store } from 'fileThatMakesStore.js';
    
    const someValue = store.getState().something;
    const someValue = store.getState().someReducer.something; // If you have multiple reducers
    

    Good to know: The store is just a simple JS object with three functions: subscribe(), dispatch(), getState().