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

react-use-light

v1.2.8

Published

React use without external dependencies.

Downloads

22

Readme

react-use-light

react-use without external dependencies. Collection of essential React Hooks.

Fork from streamich/react-use

Install

npm i react-use-light

or

yarn add react-use-light

Extra Hooks

useAudioControls

Just like useAudio returns the audio element,a ref to the element and the controls. this also returns the time played "00:01" and the timeleft "02:10" in minutes.

import { useAudioControls } from 'react-use-light';

export function App(track) {
  const [{ audio, controls, state, currentAudioTimeRef, currentAudioTimeLeftRef, ref }] = useAudioControls({
    src: track.audioUrl,
    autoPlay: false,
    loop: false,
    'aria-label': track.name,
  });

  return (
    <div>
      <h1>{track.name}</h1>
      {audio}
    </div>
  );
}

useDate

import React from 'react';
import { useDate, formatDate } from 'react-use-light';

export function Test() {
  const [date] = useDate();
  return <h1>{formatDate(date)}</h1>;
}

createContextHook

import { createContext } from 'react';
import { createContextHook } from 'react-use-light';
import { API_URL } from '../constants';
import { AppContextState } from './reducer';

const initialState: AppContextState = {
  auth: {
    user: undefined,
    errorMessage: undefined,
    loading: false,
  },
  surveys: {
    openSurveys: [],
  },
};

export const AppContext = createContext(initialState);

let fetched = false;

export const useAppContext = createContextHook(AppContext, (context) => {
  async function fetchSurveys() {
    if (!fetched) {
      const res = await fetch(API_URL + '/surveys');
      const data = await res.json();
      fetched = true;
      return data.surveys;
    } else {
      console.log('returning from cache');
      return context.surveys.openSurveys;
    }
  }
  return { ...context, fetchSurveys };
});

CreateContextReducer

const [ContextProvider, useContext, Context] = createContextReducer<AppState, Actions>();
import { createContextReducer, Action } from 'react-use-light';
import { useState } from 'react';

// CREATE STATE TYPE
interface AppState {
  notes: string[];
  user: User | undefined;
}

//CREATE ACTIONS TYPE (Should extend Action interface >> {type:string, payload?:any})
type Actions = SetUserAction | SetNotesAction;

interface SetUserAction extends Action {
  type: 'SET_USER';
  payload: User | undefined;
}

interface SetNotesAction extends Action {
  type: 'SET_NOTES';
  payload: string[];
}
interface User {
  name: string;
  email: string;
}

//Pass the State Type and Actions Type to the create function in order to get a properly typed context.
// @returns >>> [ContextProvider, ContextHook, and Context]
const [AppContextProvider, useAppContext, AppContext] = createContextReducer<AppState, Actions>();

//create state reducer for the defined types
const reducer = (state: AppState, action: Actions): AppState => {
  switch (action.type) {
    case 'SET_NOTES':
      return { ...state, notes: action.payload };
    case 'SET_USER':
      return { ...state, user: action.payload };
    default:
      return { ...state };
  }
};

// initial state
const initialState: AppState = {
  notes: [],
  user: undefined,
};

// USE ContextProvider by passing initial state and the reducer function.
export function App() {
  return (
    <AppContextProvider initialState={initialState} reducer={reducer}>
      <PageOne />
    </AppContextProvider>
  );
}

// Use in ContextProvider Children
function PageOne() {
  const [{ notes }, dispatch] = useAppContext();
  const [note, setNote] = useState('');
  function addNote() {
    if (note && note.trim() !== '') {
      dispatch({
        type: 'SET_NOTES',
        payload: [...notes, note],
      });
      setNote('');
    }
  }
  return (
    <div>
      <h1>Inside Context</h1>
      <form
        onSubmit={(e) => {
          e.preventDefault();
          addNote();
        }}
      >
        <div>
          <input placeholder="add note" value={note} onChange={(e) => setNote(e.target.value)} />
        </div>
      </form>
      <div>
        {notes.map((n) => (
          <p key={n}>{n}</p>
        ))}
      </div>
    </div>
  );
}

Others

  • [combineReducers] - combines React.Reducer objects into 1.

  • [RoutePathGetter] - Class to orginize the router paths of an application.

  • [SkeletonElement] - React Skeleton Component.

  • [createGlobalStyle] - Creates global styles (appends to head). you can pass a string or an object with CSSProperties. eg. {body: {backgroundColor: 'red'}}

  • [removeGlobalStyle] - Removes global styles by id. (id returned by createGlobalStyle)

  • [ErrorBoundary] - Error Boundary Component

  • [useDebounceFunction] - Debouce Function for React

  • [pick, debounceFunction, throttleFunction , rgbToHex, degreesToRadians, hexToRGB, interpolateColor, radiansToDegrees, removeFirst] - Utility functions.

  • [useRefModel] - creates form elements 2 way binding on the value.

  • [useThemeStyles] - toggles between theme styles. 'dark'|'light'. see example

    const [theme, setTheme, toggleTheme] = useThemeStyles(
      'light', // default theme
      `:root{--app-color: black;}` // dark styles,
      `:root{--app-color: white;}` // light styles
    );

React-Use Library Documentation