← React Beginner Questions - Set 1 Q5
React Beginner Questions - Set 1
Same component, two syntaxes. The functional one on the left is what you should write today; the class one is what you will still find in older codebases.
// Functional component with a hook
import { useState } from 'react';
export function Counter() {
const [count, setCount] = useState(0);
return <button onClick={() => setCount(count + 1)}>{count}</button>;
}
// Class component, same behaviour
import { Component } from 'react';
export class CounterClass extends Component {
state = { count: 0 };
render() {
return (
<button onClick={() => this.setState({ count: this.state.count + 1 })}>
{this.state.count}
</button>
);
}
}