Moving Objects Outside Components
You'll learn how to prevent unnecessary re-renders by extracting constant objects out of your component body when they don't depend on props or state.
The Problem: Recreating the Same Thing
Every time your component renders, any object literal defined inside it gets recreated with a new reference—even if its contents never change. React sees this as a "new" prop, triggering child re-renders unnecessarily.
The Solution: Module-Level Constants
If an object doesn't depend on props, state, or any render-specific values, move it outside the component entirely. Define it at module scope, where it's created once and reused forever.
// ✅ Created once, stable reference
const DEFAULT_STYLES = {
padding: '16px',
borderRadius: '8px'
};
const OPTIONS = [
{ id: 1, label: 'First' },
{ id: 2, label: 'Second' }
];
function MyComponent({ data }) {
return (
<div style={DEFAULT_STYLES}>
<Dropdown options={OPTIONS} data={data} />
</div>
);
}
Now DEFAULT_STYLES and OPTIONS have the same reference across all renders. Child components receiving them won't re-render unless their other props change.
When This Works
Use this pattern when:
- The object's values are truly constant
- Nothing inside depends on props, state, or context
- You're passing it as a prop to memoized children
The Analogy
Think of it like a shared library book versus photocopies. If everyone can reference the same book (module constant), that's efficient. If you photocopy the same pages every time someone asks (inline object), you're wasting resources.
Key Takeaway: When objects don't depend on component-specific data, define them once outside the component to maintain stable references and prevent unnecessary child re-renders.