How to render React (with Redux) component only when props are received?

react-redux connect
react-redux example
react redux tutorial
mapstatetoprops
mapdispatchtoprops
react-redux hooks
react native redux
redux dispatch

Let us assume we have a statefull React component (configured to work with Redux):

export class SomeComponent extends Component {
  state = {
    someObject: {}
  };

  componentWillMount() {
    this.props.getNews();
    this.props.getFakeNews();
  }

  render() {
    const {
      news,
      fakeNews
    } = this.props;

    if(_.isEmpty(news) || _.isEmpty(fakeNews)){
      return <div>Loading</div>
    }else{
      return <div>Here all component stuff</div>
    }
}

SomeComponent.propTypes = {
  news: PropTypes.array.isRequired,
  fakeNews: PropTypes.array.isRequired
};

export const Some = connect(
  state => ({
    news: newsSelectors.list(state),
    fakeNews: fakeNewsSelectors.list(state)
  }),
  {
    getNews,
    getFakeNEws
  }
)(withStyles(styles)(SomeComponent), withRouter(SomeComponent));

This component will re-render two times during getting news and fake news. In the render method we need to check if both of them are loaded.

Is there any way to trigger render only when all props are loaded?

In a perfect scenario I'd like to have no detailed null/empty check on the set of props. I believe React or Redux should perform this operation on its own as long the prop is configured as required.

You can add a lifecycle method `shouldComponentUpdate(nextProps, nextState).

You can add the following method and it should resolve it for you:

shouldComponentUpdate(nextProps, nextState) { 
  if (_.isEmpty(nextProps.news) || _.isEmpty(nextProps.fakeNews)) {
    return false;
  }
  return true;
}

Connect: Extracting Data with mapStateToProps · React Redux, visibilityFilter } } // component will receive: props.a, props.todos, and It should only take state (and ownProps ) as arguments, and return the component will be re-rendered so it can receive the updated values as props. React Redux implements several optimizations to ensure your actual component only re-renders when actually necessary. One of those is a shallow equality check on the combined props object generated by the mapStateToProps and mapDispatchToProps arguments passed to connect .

You could do something like:

// HOC factory
function ifComponent (predicate, PlaceHolder) {
  return Component => class If extends React.Component {
    render () {
      if (predicate(this.props)) {
        return <Component {...this.props} />
      }
      return <PlaceHolder {...this.props} />
      }
    }
  }
}

// create the customHOC
const whenPropsLoaded = ifComponent(props => props.news && props.fakeNews, Loader);


// compose the two HOCs using the `compose` function in redux (simple function composition)
const News = compose(
  connect(getNewsProps),
  whenPropsLoaded(DisplayNews)
);

As a side note you may be interested in the recompose utility library bad its branch HOC (docs here). I think this is pretty much what you want as you seem to know about HOCs.

React Redux, Why isn't my component re-rendering, or my mapStateToProps running? Should I only connect my top component, or can I connect multiple components in my  What this teaches us is that the patterns of render props, and state initializers, and controlled components, and the utility of react-broadcast are really powerful, and applicable in many scenarios, whether it be just a small, isolated component that you're going to reuse in multiple places, or a bigger component that controls state of the

If you want to avoid null and undefined values from redux. You can use Selectors it was very easy to avoid those things.

  const newsSelectors = (state) => {

     if(!state.list) { *//list is null or undefined*
       return [] or {} *//your wish (Proptypes required value)*
     }
     else {
       return state.list
    }
 }

export { newsSelectors };

Usage with React, I see the following presentational components and their props emerge from this brief: They only render what's given to them. mapDispatchToProps() that receives the dispatch() method and returns callback props that you want to inject into  Once you add Redux to the mix, components at any level in your tree of components can get props from the redux store via react-redux‘s connect function. This is a really powerful feature, but it also puts in jeopardy the one-way data flow that makes React apps desirable in the first place.

I think you can solve the issue if you rewrite the render function as below.

render() {
    const {
      news,
      fakeNews
    } = this.props;

    return (
        {news && fakeNews ? 
            <div>Here all component stuff</div>
        :   <div>Loading</div> }
    )
}

I hope this helps you.

React Redux Connect tutorial: When and how to use it, While props are read-only and allow a parent component to pass attributes to a child They are often created using React Redux and may dispatch Redux actions. getElementById('root'); ReactDOM.render(( <Provider store={store}> container components to receive dynamic props based on the props  In React, you can create distinct components that encapsulate behavior you need. Then, you can render only some of them, depending on the state of your application. Conditional rendering in React works the same way conditions work in JavaScript. Use JavaScript operators like if or the conditional operator to create elements representing the

Access the Redux Store Outside a React Component, How do I access Redux store outside a react component? The app will render the children component based on its route. but, on "app" component, there's a necessary API that should be called first before rendering its children component. App/Component.js class CoreLayout extends React .

How to Use Redux with React Hooks, , you can pass that data to a function that needs it. Instead of letting React re-render all the time, you can tell React when you don’t want to trigger a re-render. When React comes to render the component it will run shouldComponentUpdate and see if it returns true (the component should update, a.k.a. re-render) or false (React can skip the re-render this time). So you’ll need to overwrite

4 ways to dispatch actions with Redux - Blogs, You see, when you connect a component using react-redux's connect() HOC, Redux is wrapped in a memo() so it will only re-render when its props change. react-redux-pledge. Enhance your redux-connected component by rendering them only when their props are guaranteed (i.e, relative data are fetched) DO NOT USE IN PRODUCTION. This project is a draft, do not use it in production since it's not tested nor used in production project. MOTIVATIONS

Comments
  • You could do it in your middleware/ async layer. Only update news and fakeNews state (via an action) when both have returned. Depends on what you are using for your async calls (thunks, redux-observables etc.) as to how that would be impemented.
  • You definitely should check thunk or saga. With redux thunk you can use mapDispatchToProps which is exactly what you need.
  • Have you tried looking at reselect?
  • @Vivian No, I haven't tried yet. Is it necessary or at least helpful in this case?
  • Partially it solves the problem. Now render is executed twice - at the beginning when state is empty and second time when empty check returns true. That's huge improvement! Although - it's not yet full solution of the problem.
  • That's nice and creative. But to be honest it's a bit overkill. In the essence it just moves null check from first lines of render method to predicate. What I try to find is more generic method of just executing render after all props are filled in. I'm really surprised it's not simple and provided by React or Redux framework...
  • You cannot escape testing for props presence each time they are passed to your component. Think about what doing it inside your component means for a "generic" solution. If generic means "paramaterizable" then your component needs to expose a place to make those checks (and to supply the appropriate predicate function). The thing is when using HOC (with redux for instance), might as well compose them for props->props manipulation, and compose Components for props->view manipulation.
  • As a side note, in the future "suspense" release, some sort of mechanism will be available for dealing with this kind of use case, see youtube.com/watch?v=z-6JC0_cOns for more details (still a work in progress). The guy presenting is the one who did the recompose thing.