Component reuse
- React Native course
- Beginner
- Lesson 17/116
- 5 min
Learn to reuse components.
Component reuse
After defining a component, you can call it as many times as you want. By passing different props each time, you produce similar but different outputs. This is called reuse.
For example, <User name='Alex' /> and <User name='Ayşe' /> call the same User component with different names.
This way you avoid writing the same code again; a single definition gives you many uses.
The benefit of reuse
Reuse is a fundamental principle in software development. Instead of writing the same logic again, you define it once and use it in many places. This keeps code short, consistent, and easy to maintain.
When a bug is found, you fix it in only one place (the component definition); all calls are updated automatically.
This is why the component approach is the key tool that makes large apps manageable.
Practice Two User calls
The App component should call <User /> twice inside a <View>: first with name='Alex', second with name='Ayşe'. Also define the User component with the name prop.
Starter code
// Write User with name prop
// Call it twice with different names in App
function App() {
return null;
}Sample solution
function User({ name }) {
return (
<Text>{name}</Text>
);
}
function App() {
return (
<View>
<User name='Alex' />
<User name='Ayşe' />
</View>
);
}Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the reuse
| Term | Meaning |
|---|---|
<User name='Alex' /> |
First call |
<User name='Ayşe' /> |
Second call |
same User |
Single definition |
different name |
Different output |
2 Second call
<View>
<User name="Ayşe" />
____
</View>
<View>
<User name="Ayşe" />
<User name="Alex" />
</View>
Explanation: The same component is called again with a different name.
3 What does reuse provide?
- Longer code
- Slower execution
- More bugs
- Not writing the same code again Correct answer
Explanation: Reuse gives one definition, many uses.