Last active
December 19, 2020 09:29
-
-
Save madeinfree/581e4fd2bfee2d840c85e2f54f55ce88 to your computer and use it in GitHub Desktop.
透過 Web Workers API 改善 React 大量計算阻塞渲染幀數01.medium
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useState, useEffect } from "react"; | |
import "./styles.css"; | |
export default function App() { | |
const [sum, setSum] = useState(0); | |
useEffect(() => { | |
const worker = new Worker("./computing.js"); | |
worker.addEventListener("message", (e) => { | |
const data = e.data; | |
setSum(data); | |
}); | |
worker.postMessage([0, 1000000000]); | |
}, []); | |
return ( | |
<div className="App"> | |
<h1>Hello CodeSandbox</h1> | |
<h2>Count Sum: {sum}</h2> | |
</div> | |
); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
onmessage = (e) => { | |
const [num1, num2] = e.data; | |
let sum = 0; | |
for (let i = num1; i < num2; i++) { | |
sum += i; | |
} | |
postMessage(sum); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment