React get state from Redux store within useEffect

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(() => {
    //...
  },[])
 //...
}

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.


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]);

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.