1.0.5 • Published 6 months ago

@reactx-hooks/extension v1.0.5

Weekly downloads
-
License
MIT
Repository
github
Last release
6 months ago

@reactx-hooks/extension

A collection of useful React hooks for managing complex state.

Installation

npm install @reactx-hooks/extension
# or
yarn add @reactx-hooks/extension
# or
bun add @reactx-hooks/extension

Usage

useModel

useModel is a powerful hook for managing complex state objects with deep nesting. It provides a simple API for updating nested objects while maintaining immutability.

import { useModel } from '@reactx-hooks/extension';

interface User {
  name: string;
  age: number;
  address: {
    city: string;
    country: string;
    location: {
      latitude: number;
      longitude: number;
    };
  };
}

function UserProfile() {
  const [user, setUser, resetUser] = useModel<User>({
    initialValue: {
      name: 'John Doe',
      age: 30,
      address: {
        city: 'London',
        country: 'UK',
        location: {
          latitude: 51.5074,
          longitude: -0.1278
        }
      }
    }
  });

  // Update nested values
  const updateCity = () => {
    setUser({
      address: {
        city: 'New York'
      }
    });
  };

  // Function updates
  const updateLocation = () => {
    setUser(prev => ({
      address: {
        location: {
          latitude: prev.address.location.latitude + 1,
          longitude: prev.address.location.longitude + 1
        }
      }
    }));
  };

  return (
    <div>
      <h1>{user.name}</h1>
      <p>City: {user.address.city}</p>
      <button onClick={updateCity}>Update City</button>
      <button onClick={updateLocation}>Update Location</button>
      <button onClick={resetUser}>Reset</button>
    </div>
  );
}

Features

  • Deep nested object updates
  • Type-safe with TypeScript
  • Optional initial value
  • State change callback
  • Reset functionality
  • Immutable updates
  • Partial updates support

API

function useModel<T extends object>(options?: {
  initialValue?: T;
  onStateChange?: (newState: T) => void;
}): [
  T,
  (updates: DeepPartial<T> | ((prevState: T) => DeepPartial<T>)) => void,
  () => void
];

Options

  • initialValue: Optional initial state
  • onStateChange: Optional callback that runs when state changes

Returns

  • [0]: Current state
  • [1]: Function to update state
  • [2]: Function to reset state to initial value

License

MIT

ababacornacorn-globalsacorn-walkagent-baseansi-escapesansi-regexansi-stylesanymatchargparsearia-queryasyncasynckitbabel-jestbabel-plugin-istanbulbabel-plugin-jest-hoistbabel-preset-current-node-syntaxbabel-preset-jestbalanced-matchbrace-expansionbracesbrowserslistbs-loggerbserbuffer-fromcall-bind-apply-helperscallsitescamelcasecaniuse-litechalkchar-regexci-infocjs-module-lexercliuicocollect-v8-coveragecolor-convertcolor-namecombined-streamconcat-mapconvert-source-mapcreate-jestcross-spawncss.escapecssomcssstylecsstypedata-urlsdebugdecimal.jsdedentdeepmergedelayed-streamdequaldetect-newlinediff-sequencesdom-accessibility-apidomexceptiondunder-protoejselectron-to-chromiumemitteryemoji-regexentitieserror-exes-define-propertyes-errorses-object-atomses-set-tostringtagescaladeescape-string-regexpescodegenesprimaestraverseesutilsexecaexitexpectfast-json-stable-stringifyfb-watchmanfilelistfill-rangefind-upform-datafs.realpathfseventsfunction-bindgensyncget-caller-fileget-intrinsicget-package-typeget-protoget-streamglobglobalsgopdgraceful-fshas-flaghas-symbolshas-tostringtaghasownhtml-encoding-snifferhtml-escaperhttp-proxy-agenthttps-proxy-agenthuman-signalsiconv-liteimport-localimurmurhashindent-stringinflightinheritsis-arrayishis-core-moduleis-fullwidth-code-pointis-generator-fnis-numberis-potential-custom-element-nameis-streamisexeistanbul-lib-coverageistanbul-lib-instrumentistanbul-lib-reportistanbul-lib-source-mapsistanbul-reportsjakejest-changed-filesjest-circusjest-clijest-configjest-diffjest-docblockjest-eachjest-environment-nodejest-get-typejest-haste-mapjest-leak-detectorjest-matcher-utilsjest-message-utiljest-mockjest-pnp-resolverjest-regex-utiljest-resolvejest-resolve-dependenciesjest-runnerjest-runtimejest-snapshotjest-utiljest-validatejest-watcherjest-workerjs-tokensjs-yamljsdomjsescjson-parse-even-better-errorsjson5kleurlevenlines-and-columnslocate-pathlodashlodash.memoizelru-cachelz-stringmake-dirmake-errormakeerrormath-intrinsicsmerge-streammicromatchmime-dbmime-typesmimic-fnmin-indentminimatchmsnatural-comparenode-int64node-releasesnormalize-pathnpm-run-pathnwsapionceonetimep-limitp-locatep-tryparse-jsonparse5path-existspath-is-absolutepath-keypath-parsepicocolorspicomatchpiratespkg-dirpretty-formatpromptspslpunycodepure-randquerystringifyreactreact-domreact-error-boundaryreact-isredentregenerator-runtimerequire-directoryrequires-portresolveresolve-cwdresolve-fromresolve.exportsrrweb-cssomsafer-buffersaxesschedulersemvershebang-commandshebang-regexsignal-exitsisteransislashsource-mapsource-map-supportsprintf-jsstack-utilsstring-lengthstring-widthstrip-ansistrip-bomstrip-final-newlinestrip-indentstrip-json-commentssupports-colorsupports-preserve-symlinks-flagsymbol-treetest-excludetldtstldts-coretmplto-regex-rangetough-cookietr46type-detecttype-festundici-typesuniversalifyupdate-browserslist-dburl-parsev8-to-istanbulw3c-xmlserializerwalkerwebidl-conversionswhatwg-encodingwhatwg-mimetypewhatwg-urlwhichwrap-ansiwrappywrite-file-atomicwsxml-name-validatorxmlcharsy18nyallistyargsyargs-parseryocto-queue
1.0.5

6 months ago

1.0.4

6 months ago

1.0.3

6 months ago

1.0.2

6 months ago

1.0.1

6 months ago

1.0.0

6 months ago