Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

75
Views
React ref vs state to manipulate className

So I found two ways to dynamically change the className of react component. But which one is the best and most efficient?

Using ref:

class Header extends React.Component{
    dropdownRef = React.createRef()
    
    handleDropdown = () =>{
      this.dropDownRef.current.classList.toggle('open')
    };
    
    render(){
       return(
          <header>
              <div ref={this.dropdownRef} className="dropdown">
                Hello
              </div>
              <button onClick={this.handleDropdown}>Click Me!</button>
           </header>)
    }

}

Using state:

class Header extends React.Component{
    state = {isOpen : false }

    handleDropdown = () =>{
       this.setState(prev=>({
           isOpen: !prevState.isOpen
       }))
    };

    render(){
       return(
          <header>
             <div className={`dropdown ${this.state.isOpen ? "open" : ""}`}>
               Hello
             </div>
             <button onClick={this.handleDropdown}>Click Me!</button>
          </header>)
    }
}

So which one is the best way to change the class or do similar things.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

In react documentation, it's said not to overuse react refs so I think using state would be the better.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!