Search code examples
reactjstimeoutreact-hooksuse-stateconditional-rendering

Conditional Rendering,use-timeout Invalid hook call React


When check is true I want to display Next button.I get errors like unexpected token,invalid hook call. Please help me.Thanks in advance.

import React from "react";
import useTimeout from "use-timeout";

class App extends React.Component {
  state = { check: true };

  handleCheck = () => {
    this.setState({ check: !this.state.check });
  };
  render() {
    useTimeout(() => {
      this.handleCheck();
    }, 10000);
    return (
      <div>
      {
       if(this.state.check){
        return <button>Next</button> 
      }
     }
      </div>
    );
  }
}
export default App;

Solution

  • do this instead:

    <div> {this.state.check && <button>Next</button> </div>

    and remove useTimeout you don't need it and you CANT use it either as it's a hook and you're using a class component. You should trigger it by onClick instead or if you insist on using a timeout use setTimeout but I wouldn't advise using that inside render

    use a timeout like this:

    componentDidmount() {
        setTimeout(() => {
          this.handleCheck();
        }, 10000); 
    }