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 🙏

© 2024 – Pkg Stats / Ryan Hefner

rn-hooks

v1.1.0

Published

React-Native common hooks

Downloads

2

Readme

React Native Hooks

提供一些基础的 Hook,以及 React Native 独有的 Hook。

Note: React Native >= 0.59.0

Installation

yarn add rn-hooks

API

React

React Native

React

useUpdateEffect

useEffect类似,唯一区别是 useUpdateEffectmount阶段不会执行。

import { useUpdateEffect } from 'rn-hooks';

useUpdateEffect(() => {
    // do something
}, []);

useEffectOnce

只会执行一次useEffect

import { useEffectOnce } from 'rn-hooks';

//exec once
useEffectOnce(() => {}, []);

useMount

模拟class组件componentDidMount事件。

import { useMount } from 'rn-hooks';

useMount(() => {
    // todo
});

useUnMount

模拟class组件componentWillUnMount事件。

import { useUnMount } from 'rn-hooks';

useUnMount(() => {
    // todo
});

useForceUpdate

模拟class组件forceUpdate api。

import { useForceUpdate } from 'rn-hooks';
const update = useForceUpdate();
// update()

useBoolean

import { useBoolean } from 'rn-hooks';

const { state, setTrue, setFalse, toggle } = useBoolean();
返回值

| 参数名 | 类型 | 描述 | | :------- | :--------- | :--------- | | state | boolean | - | | setTrue | Function | - | | setFalse | Function | - | | toggle | Function | 切换布尔值 |

useAsync

简化异步操作,包含 loading 处理、取消等。

useAsync<T>( fn: (...args: any[]) => Promise<T>, deps: DependencyList, options?: Options<T>): ReturnValue<T>

import { useAsync } from 'rn-hooks'
   const {
        loading,
        data: votes = [],
        setData: setVotes,
    run } = useAsync<VoteInfo[]>(getVotes, [schoolUid, classUid, updateTag]);

参数

| 参数名 | 类型 | 描述 | 默认值 | | :----------------- | :------------------------------- | :--------- | :----- | | fn | (...args: any[]) => Promise<T> | 异步函数 | | deps | React.DependencyList | 依赖 | | options | Options<T> | 配置项 | | options.manual | boolean | 手动触发 | false | | options.onSuccess | (data: T) => void | 成功时回调 | | options.onError | (e: Error or string) => void | 失败时回调 | | options.autoCancel | boolean | 自动取消 | true |

返回值

| 参数名 | 类型 | 描述 | | :------ | :-------------------------------------- | :----------- | | loading | boolean | - | | run | (showLoading?: boolean) => Promise<T> | 手动执行函数 | | error | Error or string | 错误信息 | | setData | React.Dispatch<T> | 手动设置数据 |

useEventListener

简化事件监听与销毁。

useEventListener<T extends Emitter>( emitter: T, eventName: string, handler: Function ): void

参数

| 参数名 | 类型 | 描述 | 默认值 | | :-------- | :--------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------- | :------- | | emitter | Emitter | 包含下列监听和销毁方法的都可以[addListener, removeListener],[addEventListener, removeEventListener],[addListener, remove],[subscribe, unsubscribe] | | eventName | string | 事件名 | | handler | Function | | 事件回调 |

useCurrentValue

始终使用最新的值。

useCurrentValue<Text>(initialValue: T): MutableRefObject<Text>

import { useCurrentValue } from 'rn-hooks';
(data: Data) => {
    const ref = useCurrentValue(data);
    // ref.current === data
};

useTimeout

简化setTimeout操作,组件卸载后会及时清理掉未执行的定时器。

useTimeout(handler: Function, timeout: number, manual?: boolean): ReturnValue

import { useTimeout } from 'rn-hooks';
(data: Data) => {
    const { complete, start, clear } = useTimeout(() => {
        // todo
    }, 1000);

    return (
        <View>
            <Text>{complete}</Text>
            <TouchableWithoutFeedback onPress={start}>
                <Text>重新执行</Text>
            </TouchableWithoutFeedback>
            <TouchableWithoutFeedback onPress={clear}>
                <Text>取消</Text>
            </TouchableWithoutFeedback>
        </View>
    );
};

参数

| 参数名 | 类型 | 描述 | 默认值 | | :------ | :--------- | :------------------------------------------ | :----- | | handler | Function | 执行回调 | | timeout | number | 时间 | | manual | boolean | 是否手动执行,true需要手动调用start执行 | false |

返回值

| 参数名 | 类型 | 描述 | 默认值 | | :------- | :--------------------- | :-------------------------------- | :----- | | complete | boolean or undefined | 完成标示, undefined表示还未执行 | false | | start | Function | 手动执行函数,可重复执行 | - | | clear | Function | 手动清除 | - |

useInterval

简化setInterval操作,组件卸载后会及时清理掉定时器。

useInterval(handler: Function, timeout: number, manual?: boolean): ReturnValue

import { useInterval } from 'rn-hooks';
(data: Data) => {
    const { start, clear } = useInterval(() => {
        // todo
    }, 1000);

    return (
        <View>
            <Text>{complete}</Text>
            <TouchableWithoutFeedback onPress={start}>
                <Text>重新执行</Text>
            </TouchableWithoutFeedback>
            <TouchableWithoutFeedback onPress={clear}>
                <Text>取消</Text>
            </TouchableWithoutFeedback>
        </View>
    );
};

参数

| 参数名 | 类型 | 描述 | 默认值 | | :------ | :--------- | :------------------------------------------ | :----- | | handler | Function | 执行回调 | | timeout | number | 时间 | | manual | boolean | 是否手动执行,true需要手动调用start执行 | false |

返回值

| 参数名 | 类型 | 描述 | 默认值 | | :----- | :--------- | :---------------------- | :----- | | start | Function | 手动执行函数,可重复执行 | - | | clear | Function | 手动清除 | - |

React Native

useNativeEventListener

React Native DeviceEventEmitter 事件监听。

import { useNativeEventListener } from 'rn-hooks';
(props: Props) => {
    // 刷卡事件监听
    useNativeEventListener('cardId', () => {
        // todo
    });
};

useAsyncStorageState

增强useState,提供异步缓存。

useAsyncStorageState<T extends AsyncStorageStatic, S>( storage: T, key: string, initialState?: State<S> ): [S | undefined, (state: State<S> | undefined, immediate?: boolean) => void]

import { useAsyncStorageState } from 'rn-hooks';
import AsyncStorage from '@react-native-community/async-storage';
(props: Props) => {
    const [state, setState] = useAsyncStorageState(AsyncStorage, 'username', '小米');
};

返回值

| 参数名 | 类型 | 描述 | 默认值 | | :----- | :----------------------------------------------- | :------------------------------------------------------------------------------------ | :----- | | state | - | 同setState | false | | clear | (state: State<S>, immediate?: boolean) => void | true会立即设置 state,不会等待缓存设置成功。false会等待缓存设置成功后才设置 state | - |

useAnimation

简化动画,支持timingspringdecay动画。支持二维动画。

useAnimation(config: AnimationConfig): ReturnValue

(props: Props) => {
    const {
        value: width,
        restart
    } = useAnimation({
        manual: false,
        initialValue: 0,
        type: 'timing',
        toValue: 100,
        2000
    })
}

参数

| 参数名 | 类型 | 描述 | 默认值 | | :----------- | :------------------------------- | :-------------------------------------------- | :----- | | initialValue | number or {x:number, y:number} | | | type | timing、spring、decay | 动画类型 | | onEnd | Animated.EndCallback | 结束回调 | - | | manual | boolean | 是否手动执行,true需要手动调用restart执行 | false |

返回值

| 参数名 | 类型 | 描述 | 默认值 | | :------ | :----------------------------------- | :----------- | :----- | | value | Animated.Value or Animated.ValueXY | 同Animated | | restart | Function | 重新执行 | | restore | Function | 回到初始状态 | - |

useNavigationFocus

导航失焦获焦点状态。

Note: React-Navigation < 5

useNavigationFocus(navigation: NavigationScreenProp<NavigationState>): boolean

import { useNavigationFocus } from 'rn-hooks';
({ navigation }: Props) => {
    const isFocus = useNavigationFocus(navigation);
};

useNavigationFocusEffect

useEffect类似,监听导航 didFocusdidBlur 事件。

Note: React-Navigation < 5

useNavigationFocusEffect(navigation: NavigationScreenProp<NavigationState>, effect: EffectCallback)

import { useNavigationFocusEffect } from 'rn-hooks';
({ navigation }: Props) => {
    useNavigationFocusEffect(navigation, () => {
        // didFocus
        console.log('useNavigationFocus');
        return () => {
            // didBlur
            console.log('useNavigationBlur');
        };
    });
};

useDimensions

设备尺寸信息 useDimensions():{window: ScaledSize;screen: ScaledSize;}

import { useDimensions } from 'rn-hooks';
({}: Props) => {
    const { window, screen } = useDimensions();
    //screen.width,screen.height
};

useOrientation

横竖屏判断 useOrientation(): {isPortrait: boolean; isLandscape: boolean;}

import { useOrientation } from 'rn-hooks';
({}: Props) => {
    const { isPortrait, isLandscape } = useOrientation();
};

useAppState

App 当前状态

useAppState(): AppStateStatus

import { useAppState } from 'rn-hooks';
({}: Props) => {
    const appState = useAppState(); //'active' | 'background' | 'inactive'
};

useInteractionState

是否可交互状态

useInteractionState(): boolean

import { useInteractionState } from 'rn-hooks';
({}: Props) => {
    const complete = useInteractionState();
};

useKeyboard

获取键盘一些信息

useKeyboard():ReturnValue

import { useKeyboard } from 'rn-hooks';
({}: Props) => {
    const { shown, height } = useKeyboard();
};

返回值

| 参数名 | 类型 | 描述 | 默认值 | | :------ | :----------------------------------- | :----------- | :----- | | shown | boolean | 键盘是否打开 | | height | number | 键盘高度 | | coordinates | Coordinates | 键盘位置 | - | | coordinates.start | ScreenReact | 键盘起点 | - | | coordinates.end | ScreenReact | 键盘终点 | - |

useOrientation

设备横竖屏信息

useOrientation(): {isPortrait: boolean;isLandscape: boolean;}

import { useOrientation } from 'rn-hooks';
({}: Props) => {
    const { isPortrait, isLandscape } = useOrientation();
};