Skip to content

Commit 120fade

Browse files
committed
refactor: convert simple-counter.js to use React hooks instead of classes
1 parent c71f947 commit 120fade

File tree

1 file changed

+20
-19
lines changed

1 file changed

+20
-19
lines changed

solutions/simple-counter.js

Lines changed: 20 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,28 @@
1-
import React from 'react';
1+
import React, { useState } from 'react';
22
import ReactDOM from 'react-dom';
33

4-
class Counter extends React.Component {
5-
constructor(props) {
6-
super(props);
7-
this.state = {count: 0};
8-
}
4+
const Counter = () => {
5+
const [count, setCount] = useState(0);
96

107
increment = () => {
11-
const {count} = this.state;
12-
this.setState({count: count + 1});
13-
}
8+
setCount(prevCount => prevCount + 1);
9+
};
1410

15-
render() {
16-
const {count} = this.state;
17-
return (
18-
<div id="mainArea">
19-
<p>button count: <span>{count}</span></p>
20-
<button onClick={this.increment} id="mainButton">Increase</button>
21-
</div>
22-
);
23-
}
24-
}
11+
return (
12+
<div id="mainArea">
13+
<p>
14+
Button Count:
15+
<span>{count}</span>
16+
</p>
17+
<button
18+
onClick={increment}
19+
id="mainButton"
20+
>
21+
Increase
22+
</button>
23+
</div>
24+
);
25+
};
2526

2627
ReactDOM.render(
2728
<Counter />,

0 commit comments

Comments
 (0)