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

useful-react-boilerplate-hooks

v1.6.0

Published

Downloads

92

Readme

useful-react-boilerplate-hooks

useMounted()

useMounted hook help to prevent run code from initial render in react by using it with useEffect react hook

import { useMounted } from 'useful-react-boilerplate-hooks';
import { useEffect } from 'react';

function Component(){
    const mounted = useMounted();

    useEffect(() => {
        if(!mounted) return;
        // run code after component mounted;
        // ...
    }, [mounted]) // <== track mounted value
    
    return (
        <div></div>
    )
}

useExtendedState()

useExtendedState hook help to make sure get to latest changed value from state in event handler callbacks or any other callback functions

import { useExtendedState, useMounted } from 'useful-react-boilerplate-hooks';
import { useEffect, useRef, useState } from 'react';

function Component(){
    const ref = useRef();
    const mounted = useMounted();
    const [value, setValue] = useState(1);
    const [state, setState, getLatestState] = useExtendedState(1);

    useEffect(() => {
        if(!mounted) return; // check ref has mounted
        const eventCallBack = (event) => {
            // by using useState, value will not update in event 
            // callback handler.
            console.log("react default state", value);

            // with useExtendedState hook, getLatestState() function
            // will help to make sure latest state value from changes
            console.log("state from useExtendedState", getLatestState());
        };
        ref.current.addEventListener('click', eventCallBack);

        return () => {
            ref.current.removeEventListener('click', eventCallBack);
        }
    }, [mounted])

    return (
        <div ref={ref}>

             <button 
                onClick={() => {
                    setValue(val => val + 1); // update state using useState
                }}
            >Add using useState</button>

            <button 
                onClick={() => {
                    setState(val => val + 1); // update state using useExtendedState
                }}
            >Add using useExtendedState</button>
            
        </div>
    )
}

useInView()

useInView hook help to detect a HTML element is in viewport or not

import { useInView } from 'useful-react-boilerplate-hooks';
import { useRef } from 'react';

function Component(){
    const ref = useRef();
    const inView = useInView(ref); // <== add ref in parameter 

    return (
        <div style={{ width: '100%', height: '100%', overflowY: 'auto' }}>
            // add ref in div
            <div ref={ref}>check in view</div>
        </div>
    )
}

useMediaQuery()

useMediaQuery hook help to detect a window size and update width and heigth in px

import { useMediaQuery } from 'useful-react-boilerplate-hooks';

function Component(){
    const media = useMediaQuery();



    // default screen sizes =>  [sm] = 640;
    // default screen sizes =>  [md] = 768;
    // default screen sizes =>  [lg] = 1024;
    // default screen sizes =>  [xl] = 1280;
    // default screen sizes =>  [xl2] = 1536;
    //
    //
    // media => {
    //      sm: <boolean>,  -->  < 640 
    //      md: <boolean>,  -->  width between -> 640 ~ 768 
    //      lg: <boolean>,  -->  width between -> 768 ~ 1024
    //      xl: <boolean>,  -->  width between -> 1024 ~ 1280
    //      xl2: <boolean>, -->  width between -> 1280 ~ 1536
    //      graterThen: {
    //          sm: <boolean>, -->  > 640
    //          md: <boolean>, -->  > 768
    //          lg: <boolean>, -->  > 1024
    //          xl: <boolean>, -->  > 1280
    //          xl2: <boolean> -->  > 1536
    //      },
    //      lessThen: {
    //          sm: <boolean>, -->  < 640
    //          md: <boolean>, -->  < 768
    //          lg: <boolean>, -->  < 1024
    //          xl: <boolean>, -->  < 1280
    //          xl2: <boolean> -->  < 1536
    //      },
    //      dimension: {
    //          width: <current window width in px>,
    //          height: <current window height in px>
    //      },
    // }
    //
    //

    return (
        <div>
            {
                // less then mobile device screen 
                media.lessThen.md ? 
                    <div> mobile view </div> : 
                    <div>Desktop view</div>
            }
        </div>
    )
}

useOnFocusWindow()

useOnFocusWindow hook help to detect a HTML element is in viewport or not useOnFocusWindow hook also return a two function attatchEvent and detachEvent functions by calling to force attatch and detach event

import { useOnFocusWindow } from 'useful-react-boilerplate-hooks';
import { useRef } from 'react';

function Component(){
    const ref = useRef();


    useOnFocusWindow(() => {
        // run code when window was focused 
        // ...
    }, [dependencies]);


    const { attatchEvent, detachEvent } = useOnFocusWindow(() => {
        // run code when window was focused 
        // ...
    }, [dependencies]);

    return (
        <div></div>
    )
}

useFetchState()

useFetchState hook allow you to handle http request status easily

import { useFetchState, FetchState } from 'useful-react-boilerplate-hooks';
import { useEffect } from 'react';

function Component(){

    const fetchState = useFetchState();
    // fetchState.status has following property
    //
    //  status: 'loading' | 'not-initialized' | 'error' | 'completed',
    //  data: <data passed from complete() method>,
    //  message: <message passed from methods>,
    //  error: <error object passed from error() method>,
    //  progress: <percentage passed from loading() and pending() method>,
    //


    const loadData = () => {
        fetchState.loading(); // -> start mark as loading 
        // you can also call
        // fetchState.loading(<percentage of loading>, 'Loading...');
        // fetchState.pending({ progress: <percentage of loading>, message: 'Loading...' });

        fetch("/your-api").then(res => res.json()).then(res => {
            if(res.code == 200){
                fetchState.completed(); // -> mark as fetch complete 
                // 
                // You can also call complete() function with parameter
                // fetchState.completed({ 
                //    message: 'Load succeed', 
                //    data: res,  
                //    autoSetNotInitializedTimeout: 1000 // --> setting timeout will automatically reset to 'not-initialize' after certain period
                // }); // -> mark as fetch complete 
                //

                return res;
            }
            throw new Error('Fail to fetch data');
        }).catch(error => {
            // -> mark as fetch error 
            fetchState.error({ error, message: error.message });
        })
    }

    return (
        <div>   
            // 
            // fetchState.status.message 
            // if completed() called -> message will be 'Load succeed'
            // if error() called -> message will be given error message above
            // if loading() called -> message will show empty string '' or the message set in pending() method.
            // 
            // there is an enum value `FetchState` their atributes are as follow
            //      NOT_INITIALIZE: 
            //      COMPLETED:
            //      LOADING:
            //      ERROR:
            <div style={{
                // you can set styling depend on fetchState
                color: fetstate.status.status === FetchState.COMPLETED ? 'green' : 
                            fetstate.status.status === FetchState.LOADING ? 'orange' : 
                                fetstate.status.status === FetchState.ERROR ? 'red' : 'black'
            }}>Load status {fetstate.status.message}</div> // --> message will be shown here
            <button onClick={loadData}>Fetch data</button>
        </div>
    )
}

useResize()

useResize allow you to detect event of resizing html element

import { useResize } from 'useful-react-boilerplate-hooks';
import { useRef } from 'react';

function Component(){
    const ref = useRef();
    const [size, entry] = useResize(ref);
    //
    // size: { width: number, height: number }
    // entry: ResizeObserver
    //

    return (
        <div>
            <div ref={ref}>element to detech size change</div>
        </div>
    )
}