import React, {useState, useEffect} from "react"
import randomcolor from "randomcolor" /*random hex color library, you'll need to install
it first!*/
function App() {
const [count, setCount] = useState(0)
const [color, setColor] = useState("")
function increment() {
setCount(prevCount => prevCount + 1)
}
function decrement() {
setCount(prevCount => prevCount - 1)
}
useEffect(() => {
setColor(randomcolor()) /*setColor calls randomcolor function and puts it into state
thanks to useState hook*/
}, [count]) /*this second attribute says which event(s) to listen for to run the included
function. If blank, it will just run once when loading and that's it*/
return (
<div>
<h1 style={{color: color}}>{count}</h1>
<button onClick={increment}>Increment</button>
<button onClick={decrement}>Decrement</button>
</div>
)
}
export default App
import React, {useState, useEffect} from "react"
import randomcolor from "randomcolor"
function App() {
const [count, setCount] = useState(0)
const [color, setColor] = useState("")
useEffect(() => {
const intervalId = setInterval(() => {
// setCount(prevCount => prevCount + 1)
}, 1000)
return () => clearInterval(intervalId) /*by adding this "cleanup method" this is
equivalent of componentDidUnmount */
}, [])
useEffect(() => {
setColor(randomcolor())
}, [count]) //equivalent of componentDidUpdate lifecycle method
useEffect(() => {
setColor(randomcolor())
}, []) //equivalent of componentDidMount lifecycle method
return (
<div>
<h1 style={{color: color}}>{count}</h1>
</div>
)
}
export default App