Custom hooks

  1. Where to use

    With custom Hooks, component logic can be extracted into reusable functions. React Hooks means that components should be written as pure functions as much as possible. If external functions and side effects are required, use hooks to “hook” external code in. React Hooks are those hooks.


  2. Custom hooks rules

    **A custom Hook is a function whose name starts with “use“, and other Hooks can be called inside the function. **React will treat functions starting with use differently from other functions. Therefore, functions other than Custom hooks cannot begin with use.


  3. scenes to be used

    The main usage scenarios of Custom hooks:

    1. Extract the business logic layer

    2. Encapsulate general logic

    3. Monitor browser status

    4. Split complex components


  4. Use Cases

    Written by myself in the CourtCanva project. scenes to be used:

    If you write it with a package function, you need to package the function in useEffect(), which will lead to code redundancy. That is, the various states obtained by useStoreSelector() cannot be directly called in external functions, but need to be passed in through parameters. At this time, the encapsulation function requires a large number of parameters, and functions such as useDispatch() are also passed in as parameters.


    In this case, using a custom Hook is the best choice. This can simplify the code and does not need to pass in the Redux state from the outside, because the custom Hook can call the Redux state or other Hooks internally.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    import { useStoreSelector } from "@/store/hooks";
    import useCourt from "@/hooks/useCourt";
    import { setCourtDataUrl } from "@/store/reducer/canvasControlSlice";
    import { switchRuler } from "@/store/reducer/buttonToggleSlice";
    import { resetAll } from "@/store/reducer/canvasControlSlice";

    const useImageDataUrl = (stageRef: RefObject<Konva.Stage>) => {
    const dispatch = useDispatch();
    const { borderLength } = useCourt();
    const selectedColor = useStoreSelector((state) => state. courtColor. selectedColor);
    const rulerState = useStoreSelector((state) => state. buttonToggle. isRulerOn);

    useEffect(() => {
    if (!stageRef.current) return;
    dispatch(resetAll());
    rulerState ? dispatch(switchRuler(false)) : null;
    const image = stageRef.current.toDataURL({
    pixelRatio: 1.5,
    });
    dispatch(setCourtDataUrl(image));
    rulerState ? dispatch(switchRuler(true)) : null;
    }, [selectedColor, borderLength]);
    };

    export default useImageDataUrl;

Share