Export Functions from React Components

I’ve worked on countless projects where managing component functions effectively was key to building scalable and maintainable applications. One common question I often get asked is: How do you export functions from React components? Whether you want to share utility functions, event handlers, or helper methods across your app, understanding how to export them properly is essential.

In this article, I’ll walk you through the practical ways to export functions from React components. I’ll cover everything from simple named exports to default exports, and even how to export multiple functions from a single file. By the end, you’ll have a clear understanding of these methods and be able to apply them confidently in your React projects.

Export Functions from React Components

Before diving into examples, let me share why exporting functions matters. When building React apps, you often want to:

  • Reuse logic across multiple components.
  • Keep your code modular and organized.
  • Facilitate testing by isolating functions.
  • Share helper functions with other parts of your application.

Exporting functions properly makes your codebase cleaner and easier to maintain, especially in larger projects like enterprise web apps or client dashboards common in the USA market.

Method 1: Named Export of Functions

Named exports are straightforward and allow you to export multiple functions from one file. This method is great when you want to export several utilities or handlers from a single component file.

Here’s a practical example:

// src/components/ProductUtils.js
import React from 'react';

// A function to format US currency
export function formatPrice(price) {
  return price.toLocaleString('en-US', {
    style: 'currency',
    currency: 'USD',
  });
}

// A function to calculate discounted price
export function calculateDiscountedPrice(price, discount) {
  return price - price * (discount / 100);
}

// A React component that uses the above functions
export function ProductCard({ product }) {
  const discountedPrice = calculateDiscountedPrice(product.price, product.discount);

  return (
    <div className="product-card">
      <h2>{product.name}</h2>
      <p>Price: {formatPrice(product.price)}</p>
      <p>Discounted Price: {formatPrice(discountedPrice)}</p>
    </div>
  );
}

You can see the output in the screenshot below.

Export Functions from React Components

How to Import Named Exports

In another file, you can import one or multiple functions like this:

import { formatPrice, calculateDiscountedPrice } from './components/ProductUtils';

console.log(formatPrice(29.99)); // Outputs: $29.99

This approach keeps your utility functions reusable across different parts of your app.

Method 2: Default Export of a Function

Sometimes, you want to export a single main function or component from a file. Default exports are perfect for this. You can only have one default export per file, which makes it clear what the primary export is.

Example:

// src/components/ShippingCalculator.js
import React from 'react';

// Default export of a function that calculates shipping cost
export default function calculateShippingCost(weight, distance) {
  const baseRate = 5;
  const cost = baseRate + weight * 0.5 + distance * 0.1;
  return cost.toFixed(2);
}

You can see the output in the screenshot below.

Export Functions React Components

How to Import Default Export

Importing a default export is simple; you can name it anything you want:

import calculateShipping from './components/ShippingCalculator';

console.log(calculateShipping(10, 50)); // Outputs: 15.00

This method is clean when your file focuses on a single function or component.

Method 3: Export Functions Inside React Components

You might wonder if you can export functions defined inside a React component. The answer is yes, but with some caveats.

Functions defined inside a component are scoped to that component. If you want to export them, you need to define them outside or lift them.

Here’s an example of exporting a function declared inside a component by lifting it outside:

// src/components/OrderUtils.js
import React from 'react';

// Function to validate US ZIP code format
export function validateZipCode(zip) {
  return /^\d{5}(-\d{4})?$/.test(zip);
}

export function OrderForm() {
  const [zip, setZip] = React.useState('');

  const handleZipChange = (e) => {
    setZip(e.target.value);
  };

  const handleSubmit = () => {
    if (validateZipCode(zip)) {
      alert('Valid ZIP code!');
    } else {
      alert('Invalid ZIP code.');
    }
  };

  return (
    <div>
      <input type="text" value={zip} onChange={handleZipChange} placeholder="Enter ZIP code" />
      <button onClick={handleSubmit}>Submit</button>
    </div>
  );
}

You can see the output in the screenshot below.

React Components Export Functions

By exporting validateZipCode outside the component, you can reuse it elsewhere.

Method 4: Export Multiple Functions and Components Together

You can combine named and default exports in one file if needed.

Example:

// src/components/Shipping.js
import React from 'react';

export function calculateShippingCost(weight, distance) {
  const baseRate = 5;
  return baseRate + weight * 0.5 + distance * 0.1;
}

export function formatShippingMethod(method) {
  return method.toUpperCase();
}

export default function ShippingInfo({ weight, distance, method }) {
  const cost = calculateShippingCost(weight, distance);
  const formattedMethod = formatShippingMethod(method);

  return (
    <div>
      <p>Shipping Method: {formattedMethod}</p>
      <p>Shipping Cost: ${cost.toFixed(2)}</p>
    </div>
  );
}

Importing from this file:

import ShippingInfo, { calculateShippingCost, formatShippingMethod } from './components/Shipping';

console.log(calculateShippingCost(10, 100)); // 20
console.log(formatShippingMethod('express')); // EXPRESS

This method is useful when you want to export a main component plus helper functions.

Best Practices for Exporting Functions in React Projects

From my experience, here are some tips to keep your exports clean and maintainable:

  • Use named exports for utility functions: It’s easier to import only what you need.
  • Reserve default exports for main components or primary functions: This improves clarity.
  • Keep functions pure and side-effect free: This makes them easier to test and reuse.
  • Organize related functions in separate files: For example, all shipping-related functions in one file.
  • Use descriptive names: Especially important for functions shared across your team.

Exporting functions from React components is a fundamental skill that helps you write modular, reusable, and testable code. Whether you’re building a retail app for US customers or a dashboard for a financial service, knowing how to manage exports efficiently will save you time and headaches.

The methods I shared, named exports, default exports, exporting from inside components, and combining exports, cover most scenarios you’ll encounter. Try them out in your projects, and you’ll find your codebase easier to navigate and scale.

Other React articles you may also like:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.