Hawk
Hawk

Reputation: 526

React JS Best Practice

I am planning to use my state as a form of signaling that I will gonna change back and forth to show my loading screen, main form and success or error message. But not sure if this is the best practice. Here is a sample code

div hidden={this.state.FormStatus.statusMode !== "Loading"}>
          <LoadingScreen />
        </div> 

div hidden={this.state.FormStatus.statusMode !== "Main"}>
          <MainForm/>
        </div> 

But I am not sure if this is the best way, I am worried that it can slowdown my application or eat my clients CPU with this one. Can you suggest better method?

Upvotes: 0

Views: 110

Answers (3)

Arnob
Arnob

Reputation: 27

If you using hook then,

const Example = () => {
     const [loading, setLoading] = React.useState(true)

     return (
        <>
           {loading && <Loading />}
           {!loading && <Main/> }
        </>
     )   
}

Upvotes: 0

Not sure how the performance improvement is over what you are doing but here is an idea.

render() {
  const { FormStatus: { statusMode } } = this.state;
  const component = { Loading: <LoadingScreen />, Main: <MainForm /> };

  return component[this.state.FormStatus.statusMode];
}

For the record, what you are doing is fine. Only real improvement is to only render one div instead of two.

Upvotes: 0

Arek C.
Arek C.

Reputation: 1581

render() {
  const { statusMode } = this.state.FormStatus;

  if (statusMode === 'Loading') {
    return <LoadingScreen />;
  } else if (statusMode === 'Main' {
    return <MainForm />;
  }
}

or

render() {
  const { statusMode } = this.state.FormStatus;

  return (
    <div>
      <span>Something you want to display no matter what</span>
      {statusMode === 'Loading' && <Loading />}
      {statusMode === 'Main' && <Main />}
    </div>
  );
}

Upvotes: 4

Related Questions