-
Notifications
You must be signed in to change notification settings - Fork 693
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.
All reactions
Replies: 1 comment
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.