npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

like-hooks

v1.3.1

Published

Like React class Component grammar

Downloads

34

Readme

Like-Hooks

React Hooks Library,Support [email protected]↑;

npm npm NPM language

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);
      }
    );
  }
);

Edit serverless-morning-r2svr

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();

Edit serverless-morning-r2svr

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
);

Edit serverless-morning-r2svr

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>
);

Edit serverless-morning-r2svr

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);

Edit serverless-morning-r2svr

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
});

Edit serverless-morning-r2svr

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} />
)

Edit serverless-morning-r2svr

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);
};

Edit serverless-morning-r2svr

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>
)

Edit serverless-morning-r2svr

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);

Edit serverless-morning-r2svr

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);

Edit serverless-morning-r2svr

useThrottle

Throttling function Hooks。

const throttledValue = useThrottle(value => value, [val], 1000);

Edit serverless-morning-r2svr

useThrottleVal

As above, But based on original value Hooks。

const throttledValue = useThrottle(value => value, [val], 1000);

LICENSE

MIT