Should constant be defined outside component?

RMAG news

①Inside to define

import React from “react”;

const Sample = () => {
const TEXT = “hello world”;
return <div>{TEXT}</div>;
};
export default Sample;

const TEXT is defined inside Sample component.

②Outside to define

import React from “react”;

const TEXT = “hello world”;
const Sample = () => {
return <div>{TEXT}</div>;
};

export default Sample;

const TEXT is defined outside Sample component.

Main Differences

Scope
In method①,TEXT is used only inside Sample component. In method②, it is defined with a wide scope. It’s also accessible from other locations within the file. It means it can be used in other components within the file.

Memory usage
In method①,It consumes memory when the component is rendered and is released from memory when the component is unmounted.
In method②,file remains in memory as long as the file is loaded.

Summarize

Since memory is consumed with each re-render, it’s better to define constants outside the component. Also, when you want to reuse them multiple times, define them outside the component.

Leave a Reply

Your email address will not be published. Required fields are marked *