Search code examples
javascriptreactjsfunctioncomponentsarrow-functions

What is difference between the various ways of writing a component using React


I'm here studying React and from time to time, when I'm looking at component creation codes, I see 4 different syntaxes and I wanted to understand if there is any difference between the 4, I really want to understand even if there isn't one better than the other, I want at least see the most used. These are the ones I always see:

export const Home = () => {
}


export function Home() { 
}


function Home() {
}
export default Home;


const Home = () => { 
}
export default Home;

Solution

  • There is only two ways to declare a component in React (function and class component), It is recommended by react team to use functional component because of the this problem.

    you shared 4 types of functional components which are really ONE type (functional component) but the difference is the function syntax in JS itself. JS has two ways of defining functions as follows:

    function foo() {} //regular function.
    
    const foo = () => {} // arrow ( fat ) function.
    

    The last one is preferable also because of the overwhelming and confusing this problem in JS itself. you could search to learn about this l.. But arrow function as I said is the most preferable way.

    After you have declared your component, you will be - mostly - in need to export.. In Js there’s two ways of export (default and named export).

    Mostly you will use default export with your functional component. So I recommend number 4 of the examples you have shared.