Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

useAsyncStorage functions not memoized #145

Closed
tedcurrent opened this issue Jul 2, 2019 · 1 comment
Closed

useAsyncStorage functions not memoized #145

tedcurrent opened this issue Jul 2, 2019 · 1 comment

Comments

@tedcurrent
Copy link

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:
@krizzu
Copy link
Member

krizzu commented Jul 2, 2019

Hey @tedcurrent

Like stated in the docs this was just an experiment with hook API and is not recommended to use.

You can see this issue for potential candidates for the hook, so you could implement in in your app. We're going to add a fully supported version in v2.

thanks.

@krizzu krizzu closed this as completed Jul 2, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants