logo
React Hooks - Interview Questions and Answers
Below we have a class component with a state value
class Count extends Component {
    state = {
      value: 0,
    };
 
    incrementValue = () => {
      this.setState({
        value: this.state.value + 1,
      });
    };
 
    render() {
      return (
        <div>
          <button onClick={this.incrementValue}>Count:{this.state.value}</button>
        </div>
      );
    }
  }


how can you rewrite this component using react hooks?

The equivalent code using function component and react hooks are shown below,

import React, { useState } from "react";

const Count = () => {
 const [value, setvalue] = useState(0);

  return (
    <div>
      <button
        onClick={() => {
          setCount(value + 1);
        }}
      >
        Count: {value}
      </button>
    </div>
  );
}