The
import { Component } from "react";
interface Props {}
interface State {
color: string
}
export default class App extends Component<Props, State>{
constructor(props: Props) {
super(props)
this.state = {color: "green"};
this.changeColor = this.changeColor.bind(this)
}
componentDidMount() {
this.setState({color: "yellow"})
console.log("componentDidMount")
}
changeColor() {
this.setState((prevState) => {
if(prevState.color === "green"){
return {color: "blue"}
}
else{
return {color: "green"}
}
})
}
render(){
return <button
style={{color: this.state.color}}
onClick={this.changeColor}>
Change Color
</button>
}
}
If I run this component, I will see the console log output
The equivalent React hook is the
import { useEffect, useState } from "react"
export const FunctionalComponent = () =>{
const [color, setColor] = useState<string>("green")
useEffect(() => {
setColor("yellow")
console.log("useEffect")
},[])
const changeColor = () => {
setColor((prevColor) => {
if(prevColor === "green"){
return "blue"
}
else{
return "green"
}
})
}
return(
<button style={{color: color}} onClick={changeColor}>Change Color</button>
)
}
If I run this component, I will see the console log output