Search code examples
react-nativerequire

When I use `require` to load an image in React Native, does it really load the image into memory? When will it release?


There are two ways to require an image for an Image component in React Native.

// 1. inline `require` (triggered when using)
const IconView = () => 
  <Image source={require('./img/favicon.png')} />

// 2. define a variable for cache (triggered when loading)
const imageSource = require('./img/favicon.png')
const IconView = () => 
  <Image source={imageSource} />
  • Are both cases the same?
  • Will the second case load the whole image into the memory?
  • When will an image derived from require be released?

Solution

  • The call to require doesn't do much - it returns an ID which was registered by the RN packager and assigned to this image. The actual URL is resolved from the ID when the image component needs to render.

    On the native side, the image is loaded from the URL, and even at this point it only takes a small amount of memory for the image object representation. Only when the image is actually drawn as a native texture it gets inflated (decompressed) and loaded in full into the memory (unless, of course, the image was already cached).

    So to answer your questions:

    1. Both cases are the same
    2. Second case is not special and would not load the whole image into memory
    3. The image will be released when the native representation of the image view is released, unless it's cached in memory (in some cases, local images are cached internally), at this point it becomes the OS's concern to free this memory when it's necessary.

    Note: some of the above info is from an iOS perspective, but it should work close enough on Android as well.