First met React hook (1)

Posted May 27, 20201 min read

What is react hook?

They are not a method of sharing state, but a method of sharing state logic

Give a simple example

Customize useWindowSize as follows, you can call a hook like a function, the internal state of each component is independent of each other

import useWindowSize from './useWindowSize';

const Demo =() => {
  const {width, height} = useWindowSize();

  return(
    <div>
      <div> width:{width} </div>
      <div> height:{height} </div>
    </div>
 );
};

import {useEffect, useState} from "react";

const useWindowSize =() => {
  const [state, setState]= useState <{width:number; height:number}>({
    width:window.innerWidth,

    height:window.innerHeight
  });

  useEffect(() => {
    const handler =() => {
      setState({
        width:window.innerWidth,
        height:window.innerHeight
      });
    };

    window.addEventListener('resize', handler);

    return() => {
      window.removeEventListener('resize', handler);
    };
  }, []);

  return state;
};

export default useWindowSize;

Do you want redux with react hook?

Is it easy to answer him, these two are different things, hook is the logic of shared state, and redux is shared state and management state.
However, using hooks can easily encapsulate a simple global shared state