今回は、Effect Hook の useEffectを試してみます。
参考サイトはここ「Using the Effect Hook」
Reactでライフサイクル使いたいから、classを使わないと〜。ってなっていた、componentDidMount, componentDidUpdate, componentWillUnmount の代わりに使うことができるようです。
実装
index.html
<!DOCTYPE html>
<html>
<head>
<title>Parcel Sandbox</title>
<meta charset="UTF-8" />
</head>
<body>
<div id="app"></div>
<script src="src/index.js"></script>
</body>
</html>
index.js
ここの、useEffect() が hook になっていて、第二引数に指定したcountが変更されるたびに呼び出されるっぽい。(Mount時も、呼び出される。)
import React, { useState, useEffect } from "react";
import ReactDOM from "react-dom";
function App() {
const [count, setCount] = useState(0);
useEffect(
() => {
let color = Math.floor(Math.random() * Math.floor(999));
document.body.style.background = `#${color}`;
},
[count]
);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>Click me</button>
</div>
);
}
ReactDOM.render(<App />, document.getElementById("app"));
package.json
{
"name": "parcel-sandbox",
"version": "1.0.0",
"description": "Simple Parcel Sandbox",
"main": "index.html",
"scripts": {
"start": "parcel index.html --open",
"build": "parcel build index.html"
},
"dependencies": {
"react": "16.8.1",
"react-dom": "16.8.1"
},
"devDependencies": {
"@babel/core": "7.2.0",
"@types/react": "16.8.2",
"@types/react-dom": "16.8.0",
"parcel-bundler": "^1.6.1"
}
}
動作確認
codesandbox で動かすとこんな感じに