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

Learning from ahooks requires that you learn with the attitude that you may not, but you can’t help but know, in case you do

This article will introduce useBoolean, useToggle, useSet, useSetState, useCounter, useReactive, six apis

As before we marked the importance of the hook by ⭐️

⭐️ : General; ⭐️⭐️ : important; ⭐️⭐️ port: Very important

The special hook useReactive can help you a lot. When the special hooks are special, the special hook useReactive can help you a lot.

Example: Domesy/ahook

UseBoolean Boolean value

Recommended Index: ⭐️

Parameter Meaning:

  • Toggle: Triggers to change its state value
  • SetTrue: Sets the state to true
  • SetFalse: Sets the state to false

Code sample

import React from 'react';
  import { Button } from 'antd';
  import { useBoolean } from 'ahooks';

  const Mock: React.FC<any> = () = > {
    const [state, { toggle, setTrue, setFalse }] = useBoolean(true);

    return (
      <>
        <p>State value: {json.stringify (state)}</p>
        <div style={{display: 'flex', justifyContent: 'flex-start'}} >
          <Button type='primary' onClick={()= >Toggle switch ()} ></Button>
          <Button type='primary' onClick={()= >SetFalse ()} style={{margin:'0 30px'}}> setFalse</Button>
          <Button type='primary' onClick={()= >True setTrue ()} > Settings</Button>
        </div>
      </>
    );
  };

  export default Mock;
Copy the code

UseToggle Switches between two states

Recommended Index: ⭐️

UseToggle: The common use is the same as the use of useBoolean. It is advanced and supports switching between two states

Parameter Meaning:

  • Toggle: To switch the status
  • Set: Changes the status
  • SetLeft: Set to the first value
  • SetRight: Set to the second value, or the first value if none

Code sample

  import React from 'react';
  import { Button } from 'antd';
  import { useToggle } from 'ahooks';

  const Mock: React.FC<any> = () = > {
    const [state, { toggle, set, setLeft, setRight }] = useToggle('Hello'.'World');
    const [boolean , { toggle:toggleBool, set: toggleSet }] = useToggle(false);

    return (
      <>
        <div style={{fontWeight: 'bolder'}} >Basic usage (use always with useBoolean) :</div>
        <div style={{marginTop: 8.fontWeight: 'bolder'}} >Status: {JSON. Stringify (Boolean)}</div>
        <div style={{justifyContent: 'flex-start', display:'flex', marginTop: 8}} >
          <Button type='primary' style={{marginRight: 8}} onClick={()= >ToggleBool switch ()} ></Button>
          <Button type='primary' style={{marginRight: 8}} onClick={()= >Switch toggleSet (false)} > 1</Button>
          <Button type='primary' style={{marginRight: 8}} onClick={()= >Switch toggleSet (true)} > 2</Button>

        </div>
        <div style={{marginTop: 8.fontWeight: 'bolder'}} >Advanced usage:</div>
        <div style={{marginTop: 8}} >Two state switches: {state}</div>
        <div style={{justifyContent: 'flex-start', display:'flex', marginTop: 8}} >
          <Button type='primary' style={{marginRight: 8}} onClick={()= >Toggle switch ()} ></Button>
          <Button type='primary' style={{marginRight: 8}} onClick={()= >Set ('Hello1')} > Switch to Hello</Button>
          <Button type='primary' style={{marginRight: 8}} onClick={()= >Set ('World')} > switch to World</Button>
        </div>
        <div style={{justifyContent: 'flex-start', display:'flex', marginTop: 8}} >
          <Button type='primary' style={{marginRight: 8}} onClick={()= >SetLeft ()} > Set to Hello</Button>
          <Button type='primary' style={{marginRight: 8}} onClick={()= >SetRight ()} > Set to World</Button>
        </div>
      </>
    );
  };

  export default Mock;
Copy the code

UseSet manages Set types

Recommended index: ⭐️⭐️

UseSet: contains set(set object), and has the following functions: Add (add), remove (remove), check whether elements exist (HSA), and reset (reset)

Code sample

 import React from 'react';
  import { Button } from 'antd';
  import { useSet, useCounter } from 'ahooks';

  const Mock: React.FC<any> = () = > {
    const [set, { add, has, remove, reset }] = useSet(['Hello']);
    const [current, { inc, reset:countReset }] = useCounter(1);

    return (
      <>
        <div style={{justifyContent: 'flex-start', display:'flex',}}>
          <Button type='primary' style={{marginRight: 8}} onClick={()= >{inc() add(String(method.getDate ({add: current})))}}> Date + 1</Button>
          <Button type='primary' style={{marginRight: 8}} onClick={()= >remove('Hello')} disabled={! Has ('Hello')} > Delete Hello</Button>
          <Button type='primary' style={{marginRight: 8}} onClick={()= >{reset(); CountReset}} > reset ()</Button>
        </div>

        <div style={{ marginTop: 16}} >
          <pre>{JSON.stringify(Array.from(set), null, 2)}</pre>
        </div>
      </>
    );
  }

  export default Mock;
Copy the code

UseSetState Management Object type

Recommended index: ⭐️⭐️

UseSetState: In short, this. SetState of a class component, which can accept any component type

Code sample

import React from 'react'; import { Button } from 'antd'; import { useSetState } from 'ahooks'; interface State { hello: string; count: number; [key: string]: any; } const Mock: React.FC<any> = () => { const [state, setState] = useSetState<State>({ hello: '', count: 0, }); return ( <> <div style={{justifyContent: 'flex-start', display:'flex',}}> <Button type='primary' style={{marginRight: 8}} onClick={() => setState({hello: 'domesy'})}> Set hello </Button> <Button type='primary' style={{marginRight: 8}} onClick={() => setState({domesy: 'welcome 👏🏻'})} > Set arbitrary values, domesy</Button> <Button type='primary' style={{marginRight: 8}} onClick={() => setState((prev) => ({ count: Prev. Count + 1})} > 1 < / Button > < / div > < pre > {JSON. Stringify (state, null, 2)} < / pre > < / a >). }; export default Mock;Copy the code

UseCounter Digital manager

Recommended index: ⭐️⭐️

Can set the range of numbers, such as: maximum value, minimum value, and operation increase, decrease, set, reset four functions

No matter the initial value, increase, decrease, the set value is between the maximum value and the minimum value, if it is higher than the maximum value, current is the maximum value, and vice versa

import React from 'react'; import { Button } from 'antd'; import { useCounter } from 'ahooks'; const Mock: React.FC<any> = () => { const [current, { inc, dec, set, reset }] = useCounter(100, { min: 1, max: 10 }); </div> <div style={{display: 'flex',justifyContent: 'flex-start', marginTop: 8}}> <Button type="primary" style={{marginRight: 8}} onClick={() => inc()}> add 1</Button> <Button type="primary" style={{marginRight: 8}} onClick={() => inc(2)}> add 2</Button> <Button type="primary" style={{marginRight: 8}} onClick={() => dec()}> subtract 1 </Button> <Button type="primary" style={{marginRight: 8}} onClick = {() = > set (3)} > set to 3 < / Button > < Button type = "primary" onClick = {() = > reset ()} > reset < / Button > < / div > < / a >). }; export default Mock;Copy the code

UseReactive Another useState

Recommended index: ⭐️⭐️ port ️

UseReactive: a data responsive operation experience. You can refresh the view by modifying properties without writing useState to define data status. Any properties can be copied, including action properties, similar to global variables, that can be changed directly

In short, any type can be set, very convenient

Code sample

 import React, { useState } from 'react';
 import { Button } from 'antd';
 import { useReactive } from 'ahooks';
 
 const Mock: React.FC<any> = () = > {

   const state = useReactive<any> ({count: 0.inputVal: 'hello'.bool: false.arr: [].bug: ' '.bugs: ['domesy'.'react'.'hook'].addBug(bug:string) {
       this.bugs.push(bug);
     },
     get bugsCount() {
       return this.bugs.length; }});return (
     <>
       <div style={{fontWeight: 'bold'}} >Basic use:</div>
       <div style={{marginTop: 8}} >To manipulate numbers: {state.count}</div>
       <div style={{margin: '8px 0', display: 'flex',justifyContent: 'flex-start'}} >
         <Button type="primary" onClick={()= >State.count ++} > add 1</Button>
         <Button type="primary" style={{marginLeft: 8}} onClick={()= >State.count --} > minus 1</Button>
         <Button type="primary" style={{marginLeft: 8}} onClick={()= >State.count = 5} > Set it to 5</Button>
       </div>
       <div style={{marginTop: 8}} >Operate on Boolean: {state.bool? 'true' : 'false'}</div>
       <div style={{margin: '8px 0', display: 'flex',justifyContent: 'flex-start'}} >
         <Button type="primary" onClick={()= >state.bool = ! State.bool} > Switch state</Button>
       </div>
       <div style={{marginTop: 8}} >To manipulate strings: {state.inputVal}</div>
       <div style={{margin: '8px 0', display: 'flex',justifyContent: 'flex-start'}} >
         <Button type="primary" onClick={()= >State. inputVal = 'hello'} > Set to Hello</Button>
         <Button type="primary" style={{marginLeft: 8}} onClick={()= >State. inputVal = 'word'} > Set to word</Button>
         <Button type="primary" style={{marginLeft: 8}}
         onClick={()= >{if(state.inputVal === 'word'){state.inputVal = 'hello'}else{state.inputVal = 'word'}}} > Toggle</Button>
       </div>
       <div style={{marginTop: 8}} >To operate on arrays: {json.stringify (state.arr)}</div>
       <div style={{margin: '8px 0', display: 'flex',justifyContent: 'flex-start'}} >
         <Button type="primary" onClick={()= > state.arr.push(Math.floor(Math.random() * 100))} >push</Button>
         <Button type="primary" style={{marginLeft: 8}} onClick={()= > state.arr.pop()} >pop</Button>
         <Button type="primary" style={{marginLeft: 8}} onClick={()= > state.arr.shift()} >shift</Button>
         <Button type="primary" style={{marginLeft: 8}} onClick={()= > state.arr.unshift(Math.floor(Math.random() * 100))} >unshift</Button>
         <Button type="primary" style={{marginLeft: 8}} onClick={()= > state.arr.reverse()} >reverse</Button>
         <Button type="primary" style={{marginLeft: 8}} onClick={()= > state.arr.sort()} >sort</Button>
       </div>
       <div style={{fontWeight: 'bold', marginTop: 8}} >Calculated attributes:</div>
       <div style={{marginTop: 8}} >Quantity: {state.bugsCount} Number of entries</div>
       <div style={{margin: '8px 0'}} >
         <form
           onSubmit={(e)= > {
             state.bug ? state.addBug(state.bug) : state.addBug('domesy')
             state.bug = '';
             e.preventDefault();
           }}
         >
           <input type="text" value={state.bug} onChange={(e)= > (state.bug = e.target.value)} />
           <button type="submit"  style={{marginLeft: 8}} >increase</button>
           <Button type="primary" style={{marginLeft: 8}} onClick={()= >State. Bugs. Pop ()} > delete</Button>
         </form>

       </div>
       <ul>
         {
           state.bugs.map((bug:any, index:number) => (
             <li key={index}>{bug}</li>))}</ul>
     </>
   );
 };

 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
  • React Hook has a life cycle? You know what?