为什么要有hooks

贴上官网的解释Complex components become hard to understand

useEffect

In React class components, componentDidMount is a lifecycle method that is called once after the first render. useEffectis a perfect replacement for a componentDidMount
The second argument of the useEffect is normally an array of a state(s) that changes, and useEffectwill be only called on these selected changes. But when it’s an empty array like this example, it will be called once on mounting.

const FunctionalComponent = () => {
 React.useEffect(() => {
   console.log("Hello");
 }, []);
 return <h1>Hello, World</h1>;
};
  • On Unmounting (componentWillUnmount)
functional ver.
const FunctionalComponent = () => {
  React.useEffect(() => {
    return () => {
      console.log("Bye");
    };
  }, []);
  return <h1>Bye, World</h1>;
};
class ver.
class ClassComponent extends React.Component {
  componentWillUnmount() {
    console.log("Bye");
  }
  render() {
    return <h1>Bye, World</h1>;
  }
}

strict mode

In React 18, StrictMode gets an additional behaviour to ensure it's compatible with reusable state. When StrictMode is enabled, React intentionally double-invokes effects (mount -> unmount -> mount) for newly mounted components. Like other strict mode behaviors, React will only do this for development builds.

How to support Reusable State in Effects
Updates to Strict Mode
Adding Reusable State to StrictMode
confused with react 18 render twice

useState

tips

  • 利用useState机制触发重新渲染
const rerender = useState({})[1];
const handleClick = (e) => {
  rerender({})
}
  • 自定义mounted钩子
import { useEffect, useState } from 'react'
 
export function useMounted(): boolean {
  const [mounted, setMounted] = useState(false)
 
  useEffect(() => {
    setMounted(true)
  }, [])
 
  return mounted
}