Rozgonyi
Rozgonyi

Reputation: 1059

When to create a component in React?

Is there a best practice for when to turn repeated code into a component with React? Clearly, if its more complex repeated code but take this example from a timeline I'm working on:

Example A:

<label className="col col-2020">2020</label>
<label className="col col-2015">2015</label>
<label className="col col-2010">2010</label>
<label className="col col-2005">2005</label>
<label className="col col-2000">2000</label>

Super simple but things can always get more complex down the road. I could also just loop it:

Example B

{      
[2020,2015,2010,2005,2000].map(year => (<label className={`col col-${year}`}>{year}</label>))
}

Or I could loop a component that I'd make:

Example C

{      
[2020,2015,2010,2005,2000].map(year => <TimeLineLabel year={year}/>)
}

Is there one that's a more "React Way" of doing it considering the simplicity?

Upvotes: 1

Views: 847

Answers (1)

Mohamed Wagih
Mohamed Wagih

Reputation: 1456

There's a common best practice in programming in general called DRY (Don't Repeat Yourself).

I once read in an article (can't find it right now and I modified it now a bit) the following:

If you find yourself copying and pasting chunks of code in your file or you happened to need the same chunk in another file It is a good idea to create a reusable component from this chunk of code and start using it.

So, Option "A" is excluded for this reason and if it happened that you wanted to add some sort of styling rules or changing the class name of the label you'll make this piece of code unmaintainable if you decided to scale it.

Now, Option "B" and "C" are correct but it depends on the scenario you're trying to achieve.

Option "C" is the winner if TimeLineLabel consists of a lot of lines of code, it will be reused in more than one component or it will be customized then it is a good idea to make a new component file for it and just import it wherever you want.

Otherwise, Option "B" is the winner if it is one liner like what you're showing and you'll only use it in that file only then there's no need for option "C".

Upvotes: 2

Related Questions