Skip to content

Navigation Menu

Sign in
Sign up

Does Metro’s require have a cache like Node.js require.cache? #1524

Unanswered
jarosik10 asked this question in Q&A
Discussion options

Does Metro’s require have an equivalent of require.cache?

For example, if I have an array of images in a React Native component:

const images = [
 require("../assets/images/img1.png"),
 require("../assets/images/img2.png"),
 ...,
 require("../assets/images/imgX.png"),
];

So whenever the component rerenders, does the app load the images form the disk every time, or does it load them from the cache?
I’m wondering if a long list of requires should be wrapped in useMemo.

You must be logged in to vote

Replies: 1 comment

Comment options

Hi @jarosik10

There's no need to useMemo there. Like with Node.js, multiple calls to require will only evaluate a JS module once. With assets in particular, require("./img1.png") actually just evaluates to an integer - the index of the asset in the "asset registry".

It's when you actually use that asset index, such as by providing it to a component, e.g. <Image source={assetIdx} />, the component looks up the bundled asset metadata (including a relative path) from the asset registry at render time, and reads/processes the asset file if necessary. It's up to the Image implementation when to read it from disk - it could keep all images in memory if it wanted, or it could unload them when the React component unmounts, or anywhere in between.

So tldr - require('./asset/img.png') is cheap and memoized. Rendering the component that uses the asset may or may not be.

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet

AltStyle によって変換されたページ (->オリジナル) /