Skip to content

useAsyncStorage functions not memoized #145

@tedcurrent

Description

@tedcurrent

Current behavior

useAsyncStorage always returns new functions, which can cause infinite loops if using eg. getItem inside a useEffect with getItem as a dependency.

This is a huge issue if we use useState in conjunction with storage.

Expected behavior

getItem, setItem etc. should only update when they need to update.

Repro steps

  1. Make a function with useAsyncStorage, useState and useEffect
  2. Set state within useEffect and write to or read from async storage within the effect. Add getItem and/or setItem as dependency to useEffect.
  3. Use the function

Example

import { useEffect, useState } from 'react'
import { useAsyncStorage } from '@react-native-community/async-storage'

export const useTest = () => {
  const [state, setState] = useState('')
  const { getItem } = useAsyncStorage('@storage')

  useEffect(() => {
    setState(Math.random().toString())
    const item = getItem()
    console.log(item)
  }, [getItem])

  return state
}

In this example setState should only be called once. This will freeze the application even though we don't use state as a dependency for the useEffect. We don't even need to use getItem within the effect for this to happen.

Environment

  • Async Storage version: 1.5.0
  • React-Native version: 0.59.9
  • Platform tested: iOS and Android
  • Logs/Error that are relevant:

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions