This article has participated in the activity of “New person creation Ceremony”, and started the road of digging gold creation together.

preface

Since the React 16.8 update, functional components have taken the place of class components, so here is a high-quality, reliable Library: ahooks

Ahooks, pronounced [eɪ hʊks], is a high-quality, reliable library for React Hooks. In the current React project, a set of useful React Hooks libraries are essential. We want ahooks to be your option.

Just a while ago ahoos updated V2 to V3

Of course, some of these hooks are very nice, there is a good saying: you can not, but you have to know, in case one day use it

So it is necessary to learn ahooks, roll them up!

To introduce good hooks, we use ⭐️ as a label

⭐️ : General; ⭐️⭐️ : important; ⭐️⭐️ ️ : very important;

Example: Domesy/ahook

The life cycle

This article mainly introduces: useMount, useUnmount, useUpdateEffect, useUpdate, useTrackedEffect, useThrottleEffect, useDebounceEffect seven Api

Before React 16.8, the difference between a class component and a function component was that it had no state.

Ahooks can fix this. See how ahooks are used next. React lifecycle (16.0 and 16.4) (Which can be asked in an interview.)

UseMount and useUnmount

Recommended Index: ⭐️

UseMount: called when a component is loaded, like for class componentDidMount useUnmount: called when a component is unloaded, like for class component componentWillUnmount

Sample code:

  import React from 'react';
  import { Button, message } from 'antd';
  import { useToggle, useMount, useUnmount } from 'ahooks';

  const Test = () = > {
    useMount(() = > {
      message.info('loading');
    });

    useUnmount(() = > {
      message.info('uninstall');
    });

    return <div>The initial page</div>;
  };


  const Mock: React.FC<any> = () = > {
    const [state, { toggle }] = useToggle(false);

    return (
      <>
        <button type="button" onClick={()= >toggle()}> {state ? 'unload' : 'load '}</button>
        {state && <Test />}
      </>
    );
  };

  export default Mock;
Copy the code

UseUpdateEffect update

Recommended index: ⭐️⭐️

UseUpdateEffect: Use the same as useEffect, except that the first rendering is ignored

Code sample

  import React, { useState, useEffect } from 'react';
  import { Button, message } from 'antd';
  import { useUpdateEffect } from 'ahooks';

  const Mock: React.FC<any> = () = > {
    const [count, setCount] = useState(0);
    const [effectCount, setEffectCount] = useState(0);
    const [updateEffectCount, setUpdateEffectCount] = useState(0);

    useEffect(() = > {
      setEffectCount((c) = > c + 1);
    }, [count]);

    useUpdateEffect(() = > {
      setUpdateEffectCount((c) = > c + 1);
    }, [count]);

    return (
      <>
        <p>Use Effect: {effectCount}</p>
        <p>Use updateEffectCount: {updateEffectCount}</p>
        <Button type='primary' onClick={()= >SetCount ((c) => c + 1)}> Render</Button>
      </>
    );
  };

  export default Mock;
Copy the code

UseUpdate Specifies mandatory update

Recommended Index: ⭐️

UseUpdate: returns a function that forces the component to rerender (use with caution)

import React from 'react'; import { Button } from 'antd'; import { useUpdate } from 'ahooks'; const Mock: React.FC<any> = () => { const update = useUpdate(); Return (< > < p > time: {Date. Now ()} < / p > < Button type = 'primary' onClick = {() = > update ()} > forced update < / Button > < /}; export default Mock;Copy the code

UseTrackedEffect dependency changes

Recommended index: ⭐️⭐️ port ️

UseTrackedEffect: Used to trace which dependency change triggered useEffect execution

This hook is very important. For a complex function, we rely on a lot of parameters, and we may need to make a dependency change to trigger the hook. This hook can solve our problem

First, introduce the parameters:

  • Changes: Which dependency changes
  • PreviousDeps: the current value of the dependency
  • CurrentDeps: Value after dependency change

Code sample

  import React, { useState } from 'react';
  import { Button } from 'antd';
  import { useTrackedEffect } from 'ahooks';

  const Mock: React.FC<any> = () = > {
    const [dep1, setDep1] = useState(0);
    const [dep2, setDep2] = useState(0);
    const [dep3, setDep3] = useState(0);
    const [depActiveList, setDepActiveList] = useState([false.false.false]);
    const [text, setText] = useState('Dependency number changed:')
    const [text1, setText1] = useState('Current value:')
    const [text2, setText2] = useState('Changed value:')

    const toggleDep = (index:number) = > {
      constres = [...depActiveList]; res[index] = ! res[index] setDepActiveList(res) } useTrackedEffect((changes, previousDeps, currentDeps) = >{
      setText('Number of dependencies changed: :' + changes);
      setText1('Current value: :' + previousDeps);
      setText2('Changed value: :' + currentDeps);
    },[dep1, dep2, dep3])

    return (
      <>
        <p><input type="checkbox" checked={depActiveList[0]} onChange={()= > toggleDep(0)} />
          &nbsp;First value: {dep1}</p>
          <p>
          <input type="checkbox" checked={depActiveList[1]} onChange={()= > toggleDep(1)} />
          &nbsp;Second value: {dep2}</p>
        <p>
          <input type="checkbox" checked={depActiveList[2]} onChange={()= > toggleDep(2)} />
          &nbsp;Third value: {dep3}</p>

        <Button type='primary' onClick={()= >{ setText('') setText1('') setText2('') depActiveList[0] && setDep1((c) => c + 1); depActiveList[1] && setDep2((c) => c + 1); depActiveList[2] && setDep3((c) => c + 1); }} > 1</Button>
        <p>{text}</p>
        <p>{text1}</p>
        <p>{text2}</p>
      </>
    );
  };

  export default Mock;
Copy the code

UseDebounceEffect: Enhances the anti-shake capability of effect

Recommended Index: ⭐️

Code examples:

import React, { useState } from 'react';
  import { useDebounceEffect } from 'ahooks';

  const Mock: React.FC<any> = () = > {
    const [value, setValue] = useState<string> ('hello');
    const [records, setRecords] = useState<string[] > ([]); useDebounceEffect(() = > {
        setRecords((val) = > [...val, value]);
      },
      [value],
      {
        wait: 1000,});return (
      <>
        <input
          value={value}
          onChange={(e)= > setValue(e.target.value)}
          placeholder="Typed value"
          style={{ width: 280 }}
        />
        <p style={{ marginTop: 16}} >
          <ul>
            {records.map((record, index) => (
              <li key={index}>{record}</li>
            ))}
          </ul>
        </p>
      </>
    );
  };

  export default Mock;
Copy the code

UseThrottleEffect: Enhances the throttling capability of effect

Recommended Index: ⭐️

import React, { useState } from 'react';
  import { useThrottleEffect } from 'ahooks';

  const Mock: React.FC<any> = () = > {
    const [value, setValue] = useState<string> ('hello');
    const [records, setRecords] = useState<string[] > ([]); useThrottleEffect(() = > {
        setRecords((val) = > [...val, value]);
      },
      [value],
      {
        wait: 1000,});return (
      <>
        <input
          value={value}
          onChange={(e)= > setValue(e.target.value)}
          placeholder="Typed value"
          style={{ width: 280 }}
        />
        <p style={{ marginTop: 16}} >
          <ul>
            {records.map((record, index) => (
              <li key={index}>{record}</li>
            ))}
          </ul>
        </p>
      </>
    );
  };

  export default Mock;
Copy the code

End

I hope that I like the small novice hands-on try, deepen memory, understand good ~

Other articles

  • Don’t understand Hook? Then you are really Low
  • Do you prefer to define states this way?