xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

React Hooks 实现一个计时器组件

useEffect

https://reactjs.org/docs/hooks-reference.html#useeffect


import React, { useState, useEffect } from "react";
import "./style.css";

const App = () => {
  const [count, setCount] = useState(0);
  useEffect(() => {
    const timer = setTimeout(() => {
      const counter = count + 1;
      setCount(counter);
    }, 1000);
    return () => clearTimeout(timer);
  }, [count]);
  // useEffect(() => {
  //   const timer = setTimeout(() => {
  //     const counter = count + 1;
  //     setCount(counter);
  //   }, 1000);
  //   return () => clearTimeout(timer);
  // }, []);
  // once bug ❌
  // 观察值,如果是 [] 空数组,组件只会渲染一次,因为没有监听到任何值发生的变化
  return (
    <section>
      <div>count = {count}</div>
    </section>
  );
};

export default App;

useCallback

Returns a memoized callback


const memoizedCallback = useCallback(
  () => {
    doSomething(a, b);
  },
  [a, b],// 观察值,如果是 [] 空数组,组件只会渲染一次,因为没有监听到任何值发生的变化
);

https://reactjs.org/docs/hooks-reference.html#usecallback


useMemo

Returns a memoized value.

const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);

const memoizedValue = useMemo(() => {
  return  computeExpensiveValue(a, b);
},  [a, b]);

https://reactjs.org/docs/hooks-reference.html#usememo



React Hooks

optimize performance / 优化性能

useMemo and useCallback hooks usage guide to increasing the performance of our applications

refs

https://stackblitz.com/edit/react-hooks-useeffect-timer?file=src%2FApp.js

https://stackblitz.com/edit/react-hooks-usememo-timer?file=src%2FApp.js



©xgqfrms 2012-2020

www.cnblogs.com 发布文章使用:只允许注册用户才可以访问!


原文地址:https://www.cnblogs.com/xgqfrms/p/13692200.html