Where Should You Declare Constants in React? Inside vs Outside the Component
Should you define constants like arrays or objects inside or outside your React component?
As React developers, we're constantly balancing performance, readability, and reusability. A question that often flies under the radar is:
❓ Should you define constants like arrays or objects inside or outside your React component?
Let’s take a practical example.
The Scenario
I was building a simple Rock-Paper-Scissors game in React with TypeScript. You start with this:
"use client";
import { useState } from "react";
const icons = [
{ scissors: '/rps/icons/scissors.svg' },
{ rock: '/rps/icons/rock.svg' },
{ paper: '/rps/icons/paper.svg' },
];
const RockPaperScissors = () => {
const [computerChoice, setComputerChoice] = useState<"Rock" | "Paper" | "Scissors" | "">("");
const [playerChoice, setPlayerChoice] = useState<"Rock" | "Paper" | "Scissors" | "">("");
return <div>{/*Code goes in here*/}</div>;
};
export default RockPaperScissors;
So… should that icons array stay outside the component like it is now? Or should it be moved inside?
The Rule of Thumb
Static (unchanging) → outside the component → prevents unnecessary recreation on every render
Dynamic (depends on state/props) → inside the component → needs to access component context
Why It Matters
✅ Outside the Component
Placing icons outside the component means:
It’s created once when the module loads.
It’s not recreated on every render.
It improves performance, especially for large or complex data.
It makes your component more readable and focused.
❌ Inside the Component
Placing icons inside:
Re-creates it on every render.
Can lead to unwanted re-renders in child components if you pass it as props.
Is only justified if it depends on component state or props.
Quick Performance Test
If you ever wonder how expensive something like this might be, try logging or profiling:
console.log('icons recreated');Stick that inside your component and see how often it fires. Hint: it’ll fire on every render, even if the data is unchanged. In turn, this may be quite costly in terms of optimizing for performance.
Final Thoughts
This may feel minor in small components, but in real-world apps, especially when passing props or memoizing components, these micro-optimizations can prevent performance issues and confusing bugs.
So next time you’re writing React, remember:
💡 “If it doesn’t depend on state or props, it doesn’t belong inside the component.”
Thanks for reading!
If you have enjoyed this, feel free to subscribe for free for more insights from me.
Stay sharp,
Tom

