DEV Community

Makoto Tsuga
Makoto Tsuga

Posted on

Should constant be defined outside component?

①Inside to define

import React from "react";

const Sample = () => {
  const TEXT = "hello world";
  return <div>{TEXT}</div>;
};
export default Sample;
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

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.

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more