
Product
Socket Firewall Now Blocks Malicious VS Code and Open VSX Extensions
Socket Firewall blocks malicious VS Code and Open VSX extensions before install, protecting developers from compromised editor marketplaces.
like-hooks
Advanced tools
React Hooks Library,Support React@16.8↑;
import { useRaf } from 'like-hooks'
npm i like-hooks -S
or
yarn add like-hooks save
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]);
like useDeepMemo,But this belongs to useDeepCallback.
const [times, setTimes] = useState({
count:1,
hasChange:false
})
const cb = useDeepCallback(()=> setTimes(pre=> pre.count++),[times])
Depth contrast deps,trigger effects.
const [times, setTimes] = useState({
count:1,
hasChange:false
})
useDeepEffect(()=> {
console.log(times.count) // only run once
},[times])
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>
);
}
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);
}
);
}
);
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
})
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
})
In some cases, user scrolling is disable。
useLockBodyScroll();
import {useContextProvide} from 'like-hooks'
useContextProvide(contextKet:string,reducer:(<T>state:any,action:object):any<T>,initialState?:any,initAction?:any):<State,Dispatch>[]
useDebounce(debounceFn:()=>any,deps:any[],times:number)
const [val, setVal] = useState(0);
const [debouncedValue, setDebouncedValue] = useState("");
useDebounce(
() => {
setDebouncedValue(val);
},
[val],500
);
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>
);
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);
Add or replace the favicon of the current page
useFavicon(href:string)
Listen to read variables and respond to callback functions.
const [obj, setObj] = useState({ name: "Seven" });
useGetter(obj, (name, readValue) => {
// dosomething
});
Achieving Immutable Array-like capabilities。
useImtArray(imtArr:any[]):Imt
Support push、clear、removeIndex、removeVal、pop....
const input = useInput("");
const imtArr = useImtArray(["apple", "orange"]);
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} />
)
Alternative Life Cycle, Component Didmount and Component WillUnmount
useLifeCycles(mountFn?:() => void,unMountFn?:() => void)
useLifeCycles(() => {
// didMount
},() => {
// willUnmount
})
Merge the current state, add or replace new attributes。
const [user, mergeState] = useMergeState({firstName: 'Seven'})
mergeState({lastName: 'Floyd'})
// user {firstName: 'Seven',lastName: 'Floyd'}
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);
};
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>
)
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);
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')
Ability to read text。
useSpeech(text:string,volume?:number):void
useSpeech('hellow world')
Quickly replace a set of subject variables. Through `document.documentElement. style.setProperty()'.
useTheme(themes);
Throttling function Hooks。
const throttledValue = useThrottle(value => value, [val], 1000);
As above, But based on original value Hooks。
const throttledValue = useThrottle(value => value, [val], 1000);
MIT
FAQs
Like React class Component grammar
The npm package like-hooks receives a total of 14 weekly downloads. As such, like-hooks popularity was classified as not popular.
We found that like-hooks demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Product
Socket Firewall blocks malicious VS Code and Open VSX extensions before install, protecting developers from compromised editor marketplaces.

Research
More than 140 Mastra npm packages were compromised in a supply chain attack that used a typosquatted dependency to deliver a cross-platform infostealer during installation.

Research
/Security News
A new npm package tests AI malware scanners with prompt injection, safety-triggering comments, context flooding, and obfuscated JavaScript.