Redux and ReactJS Hooks: UseEffect Returns an Empty State

You haven’t correctly transformed your class-based component into equivalent functional component.

Following are the problems in your functional component:

  • In class component, you receive the fetchTopRatedMovies action creator as a prop and you dispatch it from the componentDidMount lifecycle method. In functional component, you are not dispatching it.

    To dispatch the action in functional components, use useDispatch() hook and use useEffect hook to dispatch this action after component has mounted.

    import React, { useEffect } from "react";
    import { useDispatch } from "react-redux";
    const TopRatedComponent = () => {
       const dispatch = useDispatch();
       useEffect(() => {
       }, []);
  • In class components, you access props object using this but in functional components, props object is passed as an argument. So, you can directly access it using the parameter name you use for the props object

    const TopRatedComponent = (props) => {
       // code
  • Data that your component receives as props from the redux store using mapStateToProps function and connect higher order component, can be accessed using useSelector hook in functional components.

    import { useSelector } from "react-redux";
    const TopRatedComponent = () => {
        const { 
        } = useSelector(state => state.topRatedMovies);
        // code

    Note: You can also use connect higher-order component and mapStateToProps to connect your functional component with the redux store.

For details of how to use hooks with react-redux, see: react-redux – Hooks

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top