Skip to main content
InterviewHubPRO
Section Overview
Q391

Question 391 of 407

Part 9: React Hooks Deep Dive (262 - 316)

96%
React Core & Hooks (407 Qs)•Part 9: React Hooks Deep Dive (262 - 316)

How to prevent component from rendering?

mid LevelCode ExampleComponentsHooks

You can prevent component from rendering by returning null based on specific condition. This way it can conditionally render component.

javascript
    function Greeting(props) {
      if (!props.loggedIn) {
        return null;
      }

      return <div className="greeting">welcome, {props.name}</div>;
    }
javascript
    class User extends React.Component {
      constructor(props) {
        super(props);
        this.state = {loggedIn: false, name: 'John'};
      }

      render() {
       return (
           <div>
             //Prevent component render if it is not loggedIn
             <Greeting loggedIn={this.state.loggedIn} />
             <UserDetails name={this.state.name}>
           </div>
       );
      }
csharp
In the above example, the `greeting` component skips its rendering section by applying condition and returning null value.