React components are the building blocks of modern web applications. By mastering components, you will be able to create dynamic, reusable, and efficient user interfaces.
Think of React components as modular pieces of a machine. Each component has a specific function and can be combined with other components to create complex applications.
Props allow data to be passed into React components. However, if no value is provided, a component might break. To prevent this, you can set default values for props.
function Greeting({ name = "Guest" }) {
return <h1>Hello, {name}!</h1>;
}
If the name prop is not provided, the component will default to "Guest".
defaultPropsfunction Greeting({ name }) {
return <h1>Hello, {name}!</h1>;
}
Greeting.defaultProps = {
name: "Guest"
};
Setting default values ensures that components function correctly even when missing certain props.
Props are how data flows from parent to child components in React. They allow dynamic customization of components.
function Welcome({ user }) {
return <h2>Welcome, {user}!</h2>;
}
function App() {
return <Welcome user="Alice" />;
}
Here, the Welcome component receives the user prop and displays it dynamically.
Sometimes, a component may render unexpectedly. React provides debugging tools to help track renders.
console.log()function Profile({ username }) {
console.log("Profile component is rendering");
return <h3>User: {username}</h3>;
}
Adding a console.log statement helps track when and how often a component re-renders.
React DevTools allows you to inspect component props and state in real-time. This tool helps identify unnecessary renders and performance bottlenecks.
Destructuring props makes code cleaner and easier to read.
function UserInfo(props) {
return <p>Name: {props.name}, Age: {props.age}</p>;
}
function UserInfo({ name, age }) {
return <p>Name: {name}, Age: {age}</p>;
}
Destructuring improves readability and reduces repetitive code.
In this tutorial, you learned:
By understanding these core concepts, you can build efficient, reusable, and maintainable React applications.