Monsieur Zartosht

Monsieur Zartosht

Who am I?

A very simple blog that belongs to a very simple full-stack web developer about his daily life and struggles through coding. here you will find many things such as music, movies, and code (lots of codes!)


What I write about


Recent Posts

When to use Class and when function components

In react there are many ways to create a component and use it throughout the program/website. At first, using class components looks easier but when the app groups larger and larger you may end up thinking about other approaches.

Table of contents

    In react there are many ways to create a component and use it throughout the program/website. At first, using class components looks easier but when the app groups larger and larger you may end up thinking about other approaches.

    Here I will describe the main differences between class and function components.

    Class components

    class MyComponent extends React.Component {
        render() {
            return (
                <h1>Hello World!</h1>
            )
        }
    }
    
    export default MyComponent
    

    Above we have a component at its very first stages, it does nothing except showing a "Hellow World!"

    Function Components

    const MyComponent = (props) => {
        return (
            <h1>Hello World!</h1>
        )
    }

    This component is a simple function component that does the same job as that class component.

    When to use which!

    In general, when your component doesn't need to have state or updated or doing some calculation it's better to use function components, they are lightweight, stateless and can be used freely in your app. The best use case for this type of component is when you want to create partial components (Input Fileds, Image Placeholders, etc...)

    I tried to make this post short and useful, let me know if you had anything more that I can add to it.


    Posted in Javascript , React on by

    Share this post: