37

What is the correct way to get state from the Redux store within the useEffect hook?

    useEffect(() => { 
        const user = useSelector(state => state.user);
    });

I am attempting to get the current state within useEffect but I cannot use the useSelector call because this results in an error stating:

Invariant Violation: Hooks can only be called inside the body of a function component.

I think I understand why as it breaks one of the primary rules of hooks.

From reviewing the example on the Redux docs they seem to use a selectors.js file to gather the current state but this reference the mapStateToProps which I understood was no longer necessary.

Do I need to create some kind of "getter" function which should be called within the useEffect hook?

2
  • can you explain your answer right here please? stackoverflow.com/questions/58159108/…
    – hamohuh
    Jun 23, 2020 at 21:01
  • In short... the useSelector should be called before the useEffect. This way we have the value and can conditionally handle it within the side-effect.
    – Sheixt
    Apr 25, 2022 at 11:11

8 Answers 8

49

Don't forget to add user as a dependency to useEffect otherwise your effect won't get updated value.

const user = useSelector(state => state.user);
useEffect(() => { 
   // do stuff     
}, [user]);
2
  • if you have in your input field the prop: value={values.userName} , and you use this in your do stuff section: values.userName= auth.userName; Then the value is not updated in the field, but appears in the redux tab. Any upgrade? Nov 5, 2022 at 13:53
  • @JonathanOrrego it's hard to tell without a code snippet, please paste the code and i may be able to help you out.
    – Motomoto
    Nov 9, 2022 at 14:26
10

You can place useSelector at the top of your component along with the other hooks:

const MyComponent = () => {
  ...
  const user = useSelector(state => state.user);
  ...
}

Then you can access user inside your useEffects.

10
  • 10
    That doesn't ensure the data is loaded before the first render... Which is the entire point of useEffect
    – Sheixt
    Sep 30, 2019 at 5:34
  • 3
    useEffect doesn't ensure that the data is loaded. Normally your redux state will have an initial value, and when the data is loaded you would update the state by dispatching some action and handling it with on of your reducers, which will re-render your component, then you will have the loaded data inside it. Sep 30, 2019 at 9:13
  • 1
    Redux store is called before the initial render, but with its initial value. If you could edit your question with more details about what you are trying to achieve, then maybe I can answer you better. Sep 30, 2019 at 10:33
  • 1
    I think perhaps I was misunderstanding the issue. I had a component erroring due to a null value. Which I had interpreted as the component's const is null. But it must be that the default state was null. So by setting my component to conditionally render based upon a set value solves it :) Thanks for your help.
    – Sheixt
    Sep 30, 2019 at 10:59
  • 1
    @Sheixt thanks for the question because the answers here have reaffirmed what I know about Redux data and initial render. Your solution is correct. ALWAYS do conditional checks for your redux data.
    – beeftosino
    Apr 2, 2020 at 2:08
8

I found using two useEffects to works for me, and have useState to update the user (or in this case, currUser).

const user = useSelector(state=>state.user);
const [currUser, setCurrUser] = useState(user);

useEffect(()=>{
  dispatch(loadUser());
}, [dispatch]);

useEffect(()=>{
  setCurrUser(user);
}, [user]);

You have to use currUser to display and manipulate that object.

5

You have two choices.

1 - If you only need the value from store once or 'n' time your useEffect is called and don't want to listen for any changes that may occur to user state from redux then use this approach

//import the main store file from where you've used createStore()
import {store} from './store' // this will give you access to redux store

export default function MyComponent(){
   useEffect(() =>{
      const user = store.getState().user;
      //... 
   },[])
}

2 - If you want to listen to the changes that may occur to user state then the recommended answer is the way to go about

const MyComponent = () => {
 //...
  const user = useSelector(state => state.user);
  
  useEffect(() => {
    //...
  },[])
 //...
}
3
  • Instead of importing store, you could also use useStore (react-redux.js.org/api/hooks#usestore) Sep 8, 2021 at 9:17
  • 2
    Yes, but useStore is a hook and hooks can not be used inside functions or other hooks. So we'll have to declare useStore on the component level, where as store.getState can be accessed with in functions. So its a better way to access store only when needed. Sep 8, 2021 at 9:43
  • 1
    With useStore you also access the store only when needed. You just pass it as dep to hook and call getState inside it. It's better approach than exposing store as you did imho. const MyComp = () => { const store = useStore(); useEffect(() => { store.getState().foo.bar }, [store]); } Sep 8, 2021 at 13:28
2
const tournamentinfofromstore=useSelector(state=>state.tournamentinfo)
useEffect(() => {
console.log(tournamentinfofromstore)
}, [tournamentinfofromstore])

So the problem is that if you change the state inside the useEffect that causes a rerender and then again the useEffect gets called "&&" if that component is passing data to another component will result in infinite loops.and because you are also storing that data in the child component's state will result in rerendering and the result will be infinite loop.!!

2

Although it is not recommended, you can use store directly in your component, even in the useEffect.

First, you have to export store from where it is created.

import invoiceReducer from './slices/invoiceSlice';
import authReducer from './slices/authSlice';

export const store = configureStore({
  reducer: {
    invoices: invoicesReducer,
    auth: authReducer,
  },
});

Then you can import it to a React Component, or even to a function, and use it.

import React, { useEffect } from 'react';
import { store } from './store';

const MyComponent = () => {
  useEffect(()=> {
    const invoiceList = store.getState().invoices
    console.log(invoiceList)
  }, [])

  return (
    <div>
      <h1>Hello World!</h1>
    </div>
  )
}

export default MyComponent
  • You can study the API for Store in here.
  • You can also see why this approach is not recommended in here.
  • Or, if you are interested in using redux store outside a react component, take a look at this blog post.
1

To add on top of @Motomoto's reply. Sometimes you depend on store to be loaded before useEffect. In this case you can simply return in if the state is undefined. useEffect will rerender once the store is loaded

const user = useSelector(state => state.user);

useEffect(() => {
  if(user === undefined){
    return}else{ 
    // do stuff
}}, [user]);
0

I'm having the same issue, The problem to the useSelector is that we cant call it into the hook, so I can't be able to update with the action properly. so I used the useSelector variable as a dependency to the useEffect and it solved my problem.

const finalImgData_to_be_assigned = useSelector((state) => state.userSelectedImg);
useEffect(()=>{
console.log('final data to be ready to assign tags : ', finalImgData_to_be_assigned.data);
}, [finalImgData_to_be_assigned ])

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.