react-use-light
TypeScript icon, indicating that this package has built-in type declarations

1.2.8 • Public • Published

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

Creates a React Reducer and a React Context and returns useContext hook, Context and Context Provider. Make sure to provide the state type and actions type if you are using typescript.

const [ContextProvider, useContext, Context] = createContextReducer<AppState, Actions>();

The Context Provider accepts the initial state and the reducer function.

The context hook returns and array with the state and the dispatch function [state, dispatch]

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

Readme

Keywords

none

Package Sidebar

Install

npm i react-use-light

Weekly Downloads

1

Version

1.2.8

License

Unlicense

Unpacked Size

774 kB

Total Files

627

Last publish

Collaborators

  • wilfredlopez