What are the advantages of having multiple components with one job each?

Question

What are the advantages of having multiple components with one job each?

Answer
The main advantage is something that we will confront through our lessons that is modularity. React is meant to be modular, so each component can be reusable in our code. let’s say we have a page with a couple of HTML elements that display some state, like an image and some text:

...
render(){
  return(
    <div>
      <img src= {this.state.img}/>
      <p>{this.state.text}</p>
    </div>
  ...
}

Now, this is a really simple example, but lets say that we have the same piece of code in another component, then it will make sense to make it into a stateless component and now we can import it into each component we will need it:

import Display from '../Display/Display;';
...
 render(){
  return(
    <div>
      <Display img={this.state.img} text={this.state.text}/>
   ...
  )
 }

There we can see the advantage of components that have one job, they are so generic that they are reusable, and there’s where their worth comes from.

6 Likes

Arent you supposed to use ‘this.props’ in Child elements instead of ‘this.state’?

1 Like

I think they are trying to emphasize modularity here. And in that sense, what makes a component modular is that, when it’s used, it operates the same way (displaying a name and image) but the content will be different. The content, meant to be mutable/changeable, would be best expressed as a state. While a parent could pass a immutable prop to this Display component, to make it meaningful as an example of modularity, state is used.

This was helpful in thinking about your question:

especially:
“Props and State do similar things but are used in different ways. The majority of your components will probably be stateless.
Props are used to pass data from parent to child or by the component itself. They are immutable and thus will not be changed.
State is used for mutable data, or data that will change.”

1 Like