Skip to content
This repository has been archived by the owner on Oct 11, 2024. It is now read-only.

Commit

Permalink
Fix uneven hooks amount in declaration, bump to 0.9.10
Browse files Browse the repository at this point in the history
  • Loading branch information
deniskabana committed Sep 9, 2023
1 parent 3b21b4d commit 61669d2
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 10 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "react-persistent-state-hook",
"version": "0.9.9",
"version": "0.9.10",
"description": "`React.useState` + BrowserStorage API for persistence",
"main": "dist/index.js",
"typings": "dist/index.d.ts",
Expand Down
14 changes: 5 additions & 9 deletions src/usePersistentState.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useState, useEffect, useLayoutEffect } from "react"
import { useState, useEffect } from "react"
import type { Dispatch, SetStateAction } from "react"
import {
checkBrowserStorage,
Expand All @@ -14,7 +14,7 @@ export enum StorageType {
Session = "session",
}

// Overloads modified from React v16.8.0 `useState` hook
// Overloads taken from React v16.8.0 `useState` hook
export function usePersistentState<S>(
initialState: S | (() => S),
storageKey: string,
Expand Down Expand Up @@ -46,18 +46,13 @@ export function usePersistentState(
) {
// Initialize classic React state
const [value, setValue] = useState(() => storageGet(storageType, storageKey, initialState) ?? initialState)
const [shouldFallback, setShouldFallback] = useState(false)

// Initial one-time checks
useLayoutEffect(() => {
useEffect(() => {
checkMissingStorageKey(storageKey) || checkStorageType(storageType) || checkWindow() || checkBrowserStorage()
setShouldFallback(true)
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])

// Resort to React useState if necessary
if (shouldFallback) return [value, setValue]

// This will not be called intentionally if initial checks won't pass
// eslint-disable-next-line react-hooks/rules-of-hooks
useEffect(() => {
Expand All @@ -70,7 +65,8 @@ export function usePersistentState(
checkIfSerializable(serializedValue)
// Update or remove
storageSet(storageType, storageKey, serializedValue)
}, [value, storageKey, storageType])
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [value])

// Return state management
return [value, setValue]
Expand Down

0 comments on commit 61669d2

Please sign in to comment.