twins sister

React Components vs Regular Functions: A Guide for New Developers

TLDR: create a functional component if you return JSX, otherwise create a regular function.

Ever felt like you're lost in the React jungle? You're not alone! As someone who's worked with fresh-faced developers straight out of college or 20-hour YouTube coding boot camps, I've seen the confusion firsthand. Let's clear the air and make React as easy as pie!

The React Revelation: It's Just JavaScript (With a Twist)

Here's the secret sauce: React is essentially JavaScript with a sprinkle of JSX magic. Mind-blowing, right? Let's dive into an example:


function Home({honey}) {
return <h1>I'm Home {honey}!</h1>
}

Looks simple, doesn't it? But this simplicity is where the plot thickens...

The Case of the Mysterious Function

Now, what if we wrote it like this?


function home({honey}) {
return <h1>I'm Home {honey}</h1>
}


Is it wrong? Nope! But here's the kicker - it's not a React component.

Cue dramatic music

The Capital Case Conundrum

React has its own set of rules, and one of them is that component names must start with a capital letter. So, function Home is a full-fledged React component, while function home is just a regular JavaScript function.

But wait, there's more! Let's break down the differences:

  1. React components inherit React superpowers, like Hooks and custom hooks.
  2. Regular functions are hook-less (no superpowers here, folks).
  3. You summon a React component like this: <Home honey={'Suzy'} />
  4. Don't call a React component directly `Home({honey:'Suzy'})`.
  5. A regular function gets called the old-fashioned way: home({honey: 'Suzy'})
  6. React components can use cool React features like React.memo(Home), but regular functions are left out in the cold.

The Render Function Trap

Sometimes, even seasoned developers fall into old habits:


function renderList({list}) {
return <li key={list.id}>{list.label}</li>
}


While this isn't technically wrong, it feels about as React-ish as putting ketchup on ice cream. Why? Because we can't optimize it with React hooks, and refactoring it later is a pain.

The React Golden Rule

Here's a simple rule to live by: If you're returning JSX, create a functional component. Otherwise, stick to a regular function. It's that easy!

Why I Love React (and You Should Too)

React's beauty lies in its closeness to JavaScript. The only real difference? It can return JSX (or even Pug, if you're feeling adventurous).

Remember, in the world of React, capitalize your components, and may the hooks be ever in your favor!

That's all for now folks!

Next, I'll talk about my journey mixing Elixir...

The Phoenix is about to rise...

Go back