Last updated: Apr 7, 2024
Reading time·3 min
You should store images close to where they are used in your React application.
For example, if you have a Contacts.js
component that uses a contact.png
image, store the image right next to the Contacts.js
file.
On the other hand, images that you do not import in your components, e.g.
favicons
should be stored in the public
directory.
Assume we have the following folder structure.
src/ pages/ contacts/ Contacts.js index.js contacts.webp
Notice that the contacts.webp
image is placed right next to the Contacts.js
file that uses it.
import ContactsIcon from './contacts.webp'; export function Contacts() { return ( <div> <h2>Contacts</h2> <img src={ContactsIcon} alt="contacts" /> </div> ); }
Colocating images close to where they are used has multiple advantages:
img
tag from the component, we know we can safely delete
the image because it's not used anywhere else in our apppublic/
directory).If the contacts.webp
image is also used in another component I would move the
image in a separate directory.
src/ pages/ contacts/ Contacts.js index.js about/ About.js index.js images/ contacts.webp
Now I would import the image from the images/contacts.webp
in both
Contacts.js
and About.js
.
import ContactsIcon from '../../images/contacts.webp'; export function Contacts() { return ( <div> <h2>Contacts</h2> <img src={ContactsIcon} alt="contacts" /> </div> ); }
If I end up removing the <img />
tag that references the image from one of the
components, then I'd move the image right next to the only component that uses
it.
CTRL + Shift + F
in your IDE and look for contacts.webp
.Your IDE should be able to show you all references of contacts.webp
in your
project.
I've also written a detailed guide on how to import and use images in React.
public/
folderpublic/
folder.You could create an images/
or favicons/
directory in your public/
folder
where you store your favicons, site logos or any other kind of images that you
aren't going to import into any of your components.
public/ favicons/ favicon-16x16.png favicon-32x32.png android-chrome-192x192.png apple-touch-icon.png index.html
favicons
in your index.html
file if you have to.You should avoid using images from the public/
directory in your React
components because they are used without being imported.
For example, if you have an image located at public/images/thumbnail.webp
, you
would set the src
of the img
tag to "/images/thumbnail.webp"
.
export default function App() { return ( <div> {/* 👇️ Local image */} <img src="/images/thumbnail.webp" alt="horse" /> </div> ); }
On the other hand, if you explicitly import an image you will get an error at build time if the import statement fails.
In short:
favicons
)
should be stored in your public/
directory, e.g. under a favicons/
folder.You can learn more about the related topics by checking out the following tutorials: