Conditionally rendering a react component

2.4k views Asked by At

For a component that is hidden at some point in its lifecycle, what is the best way to render it? 1) render the component, but do not show it (display:none). 2) render the component only when needed. What is better for performance? If the component's props and state update later, would it be better to have the component present, but hidden in the virtual DOM?

render() {
    return (
        <div style={{display: this.props.visible ? 'block' : 'none'}}>
            <RestofComponentHere />
        </div>
    );
}

or this:

render() {
    if (!this.props.visible) {
        return null;
    }
    return (
        <div>
            <RestofComponentHere />
        </div>
    );
}
2

There are 2 answers

0
Martin Dawson On

Just go with what works best for that situation. Sometimes it's method 1 and sometimes method 2. If you find out that it's slowing down your app then it's pretty easy to convert to method 1, but this should only if happen if you are conditionally rendering a ton of times. When you have a ref to the component then you want to always render it so that you can access the ref in componentDidMount and so you would have it hidden.

First method is faster as shown in answer here but don't do micro optimizations for the sake of it if conditionally rendering is cleaner code.

I'v used a mixture in my apps.

0
Priti Biyani On

I would suggest to go with the state values and have a condition based on state values to decide whether the component to be shown or hidden.

    constructor(props){
       //Set some initial condition for display depending on prop or default value
        //Something similar to this: 
        display: props.toDisplay === undefined ? true : props.toDisplay
    } 

    componentDidMount(){
        //update the state depending on the response or change
    } 

    onClick(event){
      //It might depend on someOther component's click action. 
    }

The render method would just have the following:

    render(){
       const toDisplay = this.state.display 
       if(toDisplay && 
        // Component To render
        )
    }