ridingTom
ridingTom

Reputation: 21

Refactoring from Hooks to a class component

Can you please help with refactoring a bit of code from React Hooks to a class component? I'm new in React and this gives me a hard time. I know that { useState } provides some "getter" and "setter", but don't know how to refactor it to a state with props in a "typical" React class component.

Hooks:

export default function App() {
const [counter, setCounter] = useState([]);
}

React:

class App extends React.Component {
state = {
counter:
}

Upvotes: 0

Views: 485

Answers (2)

Fraction
Fraction

Reputation: 12954

From the react Hooks FAQ page:

Should I use Hooks, classes, or a mix of both?
When you’re ready, we’d encourage you to start trying Hooks in new components you write. Make sure everyone on your team is on board with using them and familiar with this documentation. We don’t recommend rewriting your existing classes to Hooks unless you planned to rewrite them anyway (e.g. to fix bugs).

You can’t use Hooks inside of a class component, but you can definitely mix classes and function components with Hooks in a single tree. Whether a component is a class or a function that uses Hooks is an implementation detail of that component. In the longer term, we expect Hooks to be the primary way people write React components.

to answer your question, the equivalent class component would be:

class App extends React.Component {
  state = {
    counter: [] // equivalent of useState([]);
  }
  ...
  this.setState(prevState => ({
    counter: [...prevState.counter, newelement]
  })) // equivalent of setCounter(counter => [...counter, newelement]);
}

Upvotes: 0

TRomesh
TRomesh

Reputation: 4481

You can take a look into this example. This a typical class components for increment/counting .

class App extends React.Component {
  state = { count: 0 }

  increment = () => {
      this.setState({
         count: this.state.count + 1
      });
  }

  render(){
     return(
    <button onClick={this.increment}>+</button>
    );
  }

}

export default App;

Here is the Hooks implementation of it.

 function App(){
  const [count, setCount] = useState(0);

 const increment = () => {
    setCount(count+1);
  };

  return(
    <button onClick={increment}>+</button>
   );
 }
export default App;

Upvotes: 1

Related Questions