1

What difference you see between regular/arrow functions and react functional component

React functional component

import React from 'react';

function MyComp(){
   return null
}

Regular function

function myFun(){
   return null;
}
1
  • 4
    If I'm not mistaken, there's no difference, it's just what it returns. In the case of React, it returns JSX. Commented Jun 28, 2020 at 17:44

1 Answer 1

3

Conceptually, components are like JavaScript functions. They accept arbitrary inputs (called props) and return React elements describing what should appear on the screen.

function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}

From a JavaScript perspective, this is nothing but a function, except for a special return. It's JSX and each JSX element is just syntactic sugar for calling React.createElement(component, props, ...children).

Basically, you can replace the JSX in the example above with something like:

React.createElement('h1', null, `Hello ${props.name}`);

And this is nothing but a JavaScript :)

And then you can render your component:

const element = <Welcome name="Sara" />;
ReactDOM.render(
  element,
  document.getElementById('root')
);
  • You call ReactDOM.render() with the <Welcome name="Sara" /> element.
  • React calls the Welcome component with {name: 'Sara'} as the props.
  • Our Welcome component returns a <h1>Hello, Sara</h1> element as the result.
  • React DOM efficiently updates the DOM to match <h1>Hello, Sara</h1> and you get it on the screen.

There is one important requirement for React functional component!

Always start component names with a capital letter.

React treats components starting with lowercase letters as DOM tags. For example, represents an HTML div tag, but represents a component and requires Welcome to be in scope.

This function from your example can be used as a functional component:

function MyFun() { // name should start with a capital
   return null;
}

React won't display anything because React does not render if component returns null.

Sign up to request clarification or add additional context in comments.

1 Comment

teeny-tiny correction: React.createElement('h1', null, `Hello, ${props.name}`)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.