like-hooks v1.3.1
Like-Hooks
React Hooks Library,Support React@16.8↑;
Usage
import { useRaf } from 'like-hooks'
install
npm i like-hooks -S
or
yarn add like-hooks save
useDeepMemo
Can receive an object for depth comparison,like useMemo.
const [opacity, setOpacity] = useState({
opacity:1,
hasChange: false
})
return useMemo(() => (
<FormItem
label="Opacity"
>
<Slider
stepSize={0.01}
labelStepSize={0.2}
onChange={setOpacity}
value={opacity}
/>
</FormItem>
), [opacity]);
useDeepCallback
like useDeepMemo,But this belongs to useDeepCallback
.
const [times, setTimes] = useState({
count:1,
hasChange:false
})
const cb = useDeepCallback(()=> setTimes(pre=> pre.count++),[times])
useDeepEffect
Depth contrast deps,trigger effects.
const [times, setTimes] = useState({
count:1,
hasChange:false
})
useDeepEffect(()=> {
console.log(times.count) // only run once
},[times])
useWhyDidYouUpdate
Version of hook WhyDidYouUpdate
。
function App() {
const [count, setCount] = useState(0);
const [userId, setUserId] = useState(0);
// Our console output tells use that the style prop for <Counter> ...
// ... changes on every render, even when we only change userId state by ...
// ... clicking the "switch user" button. Oh of course! That's because the
// ... counterStyle object is being re-created on every render.
// Thanks to our hook we figured this out and realized we should probably ...
// ... move this object outside of the component body.
const counterStyle = {
fontSize: '3rem',
color: 'red'
};
return (
<div>
<div className="counter">
<Counter count={count} style={counterStyle} />
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
<div className="user">
<img src={`http://i.pravatar.cc/80?img=${userId}`} />
<button onClick={() => setUserId(userId + 1)}>Switch User</button>
</div>
</div>
);
}
useStateWithCb
Support for setstate callbacks, just like class Component
const [count, setCounter] = useStateWithCb('');
setCounter(
pre => pre + 'Hello',
(first, firstSetter) => {
console.log(first);
}
);
// or Continuous trigger
setCounter(
pre => pre + " World",
(first, firstSetter) => {
console.log(first);
firstSetter(
pre => pre + " !",
(second, secondSetter) => {
console.log(second);
}
);
}
);
useStateChange
when state has changed the callback function will be triggered in useEffect。
const [state, setState] = useStateChange('', (newestState) => {
// when state changed do something before second render
})
useStateChangeLayout
Similar to the hook function above, however function will be triggered in useLayoutEffect。
const [state, setState] = useStateChange('',(newestState) => {
// when state changed do something after first render
})
useLockBodyScroll
In some cases, user scrolling is disable。
useLockBodyScroll();
useContextProvide
import {useContextProvide} from 'like-hooks'
useContextProvide(contextKet:string,reducer:(<T>state:any,action:object):any<T>,initialState?:any,initAction?:any):<State,Dispatch>[]
useDebounce
useDebounce(debounceFn:()=>any,deps:any[],times:number)
const [val, setVal] = useState(0);
const [debouncedValue, setDebouncedValue] = useState("");
useDebounce(
() => {
setDebouncedValue(val);
},
[val],500
);
useDraggable
You can drag and drop an element。
const el = useRef();
const { x, y, pageX, pageY } = useDraggable(el);
return (
<div>
<div ref={el} className="DraggableBox" />
<div>
offset::x:{x},y:{y}
pageX:{pageX},pageY:{pageY}
</div>
</div>
);
useEventListener
const [coords, setCoords] = useState({ x: 0, y: 0 });
const inputRef = useRef(null);
const handler = useCallback(({ clientX, clientY }) => {
setCoords({ x: clientX, y: clientY });
}, []);
useEventListener("mousemove", handler, inputRef);
useFavicon
Add or replace the favicon of the current page
useFavicon(href:string)
useGetter
Listen to read variables and respond to callback functions.
const [obj, setObj] = useState({ name: "Seven" });
useGetter(obj, (name, readValue) => {
// dosomething
});
useImtArray
Achieving Immutable Array-like capabilities。
useImtArray(imtArr:any[]):Imt
Support push、clear、removeIndex、removeVal、pop....
const input = useInput("");
const imtArr = useImtArray(["apple", "orange"]);
useInput
Greatly simplified <Input value='' onChange={({currentTarget})=>{}}>
...
useInput(initialVal?:string):InputOption
InputOption.bind // bind Input
InputOption.clear // clear current Input value
InputOption.repalce // handler current Input string
const input = useInput("Seven");
return (
<input className="input" {...input.bind} />
)
useLifeCycles
Alternative Life Cycle, Component Didmount and Component WillUnmount
useLifeCycles(mountFn?:() => void,unMountFn?:() => void)
useLifeCycles(() => {
// didMount
},() => {
// willUnmount
})
useMergeState
Merge the current state, add or replace new attributes。
const [user, mergeState] = useMergeState({firstName: 'Seven'})
mergeState({lastName: 'Floyd'})
// user {firstName: 'Seven',lastName: 'Floyd'}
usePrevious
Gets a value before the change, and returns it for the first time, optionally(initEqual: true), because in some cases Effect calls ahead of time and returns undefine
.
usePrevious(preState:any,initEqual?:boolean)
const [count, setCount] = useState(0);
const previousCouner = usePrevious(count); // 0
const changeCounter = () => {
setCount(pre => pre + 1);
};
usePromise
ReactHook version of Proise。
const request = () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (Math.random() > 0.5) {
resolve("Success");
} else {
reject("Fail");
}
}, 1000);
});
};
const [state, setState] = useState(0);
const { value, loading, error } = usePromise(request, [state]);
return (
<p>
result:{loading ? <span>Loading...</span> : <span>{error || value}</span>}
</p>
)
useRaf
Create tasks through requestAnimationFrame。
useRaf(fn:() => void, initRun:boolean):RafControl
const [min, setMin] = useState(0);
const [second, setsecond] = useState(0);
const run = () => {
setsecond(pre => {
let newSecond = pre + 1;
if (newSecond > 60) {
setMin(preMin => preMin + 1);
return 0;
}
return newSecond;
});
};
const [start, stop] = useRaf(run, false);
useScript
Loading Script dynamically and preventing duplicate loading.
useScript(src:string):void
useScript('https://cdn.bootcss.com/react/16.9.0-rc.0/cjs/react.development.js')
useSpeech
Ability to read text。
useSpeech(text:string,volume?:number):void
useSpeech('hellow world')
useTheme
Quickly replace a set of subject variables. Through `document.documentElement. style.setProperty()'.
useTheme(themes);
useThrottle
Throttling function Hooks。
const throttledValue = useThrottle(value => value, [val], 1000);
useThrottleVal
As above, But based on original value Hooks。
const throttledValue = useThrottle(value => value, [val], 1000);
LICENSE
MIT
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago