React Components
What are React components?
React components are the building blocks of a React application. They are JavaScript functions or classes that return elements describing a part of the user interface (UI). Components allow you to break down the UI into reusable, independent pieces that can manage their own state and behavior.
What is the difference between functional and class components in React?
In React, there are two types of components:
- Functional components: These are JavaScript functions that return JSX. They are stateless by default but can manage state using hooks like
useState
anduseEffect
. - Class components: These are ES6 classes that extend
React.Component
. They can manage their own state using thethis.state
object and lifecycle methods likecomponentDidMount
andcomponentDidUpdate
.
Example of a functional component:
function Greeting() {
return <h1>Hello, World!</h1>;
}
Example of a class component:
class Greeting extends React.Component {
render() {
return <h1>Hello, World!</h1>;
}
}
What are props in React?
Props (short for "properties") are inputs to a React component. They are passed from parent components to child components and are read-only, meaning that child components cannot modify their props. Props are used to pass data and event handlers down the component tree.
Example of passing props:
function Welcome(props) {
return <h1>Hello, {props.name}!</h1>;
}
<Welcome name="Alice" />
In this example, the Welcome
component receives a prop name
and renders a greeting message.
What is state in React components?
State is a built-in object in React components that allows components to store and manage dynamic data. Unlike props, state is mutable, and when it changes, the component re-renders to reflect the updated state. State is often used to track user input, component data, or the result of asynchronous operations.
Example of using state in a functional component with useState
:
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times.</p>
<button onClick={() => setCount(count + 1)}>Click me</button>
</div>
);
}
In this example, the Counter
component manages its own state (the count
variable) and updates it whenever the button is clicked.
What is the difference between state and props in React?
The main differences between state and props are:
- State: Managed within the component, mutable, and can change over time. When state changes, the component re-renders to reflect the updated state.
- Props: Passed down from parent components to child components, immutable, and cannot be changed by the receiving component.
State is used for data that changes over time, while props are used to pass data and functions between components.
What are controlled components in React?
A controlled component is an input element (such as <input>
, <textarea>
, or <select>
) whose value is controlled by the React state. The input value is updated via an onChange
handler, and the current value is stored in the component's state.
Example of a controlled component:
function Form() {
const [value, setValue] = useState('');
const handleChange = (event) => {
setValue(event.target.value);
};
return (
<input type="text" value={value} onChange={handleChange} />
);
}
In this example, the input field's value is controlled by the component's state, and the value is updated whenever the user types into the input field.
What are higher-order components (HOCs) in React?
A higher-order component (HOC) is a function that takes a component as an argument and returns a new component with additional props or functionality. HOCs are used to reuse logic across multiple components by "wrapping" them with shared behavior.
Example of a higher-order component:
function withLogging(WrappedComponent) {
return function LoggedComponent(props) {
console.log('Rendering', WrappedComponent.name);
return <WrappedComponent {...props} />;
};
}
const LoggedButton = withLogging(Button);
In this example, the withLogging
HOC adds logging functionality to the Button
component by wrapping it and logging a message each time it renders.
What are pure components in React?
A pure component in React is a component that renders the same output given the same input props and state. Pure components optimize rendering by implementing a shallow comparison of props and state in the shouldComponentUpdate()
lifecycle method, preventing unnecessary re-renders when the props or state have not changed.
Example of a pure component using React.PureComponent
:
class PureButton extends React.PureComponent {
render() {
return <button>Click me!</button>;
}
}
In this example, PureButton
will only re-render if its props or state change, making it more efficient in certain cases.
What are functional components in React?
Functional components are JavaScript functions that return JSX elements. They are stateless by default but can manage state and perform side effects using React hooks like useState
and useEffect
. Functional components are simpler than class components and are preferred in modern React development.
Example of a functional component:
function Greeting() {
return <h1>Hello, World!</h1>;
}
Functional components can also handle state using hooks:
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times.</p>
<button onClick={() => setCount(count + 1)}>Click me</button>
</div>
);
}
What is the difference between presentational and container components?
In React, components are often categorized into two types:
- Presentational components: These components focus on how things look and are typically stateless. They receive data and callbacks via props and are responsible for rendering UI.
- Container components: These components focus on how things work and manage state. They handle business logic, data fetching, and pass data to presentational components as props.
Example of a presentational component:
function UserProfile({ name, age }) {
return <div>Name: {name}, Age: {age}</div>;
}
Example of a container component:
function UserContainer() {
const [user, setUser] = useState({ name: 'Alice', age: 30 });
return <UserProfile name={user.name} age={user.age} />;
}
What are default props in React?
Default props are used to specify default values for props in a component in case no values are provided by the parent component. This ensures that the component has a fallback value for its props when none are passed.
Example of setting default props:
function Greeting(props) {
return <h1>Hello, {props.name}!</h1>;
}
Greeting.defaultProps = {
name: 'Guest',
};
In this example, if no name
prop is passed to the Greeting
component, it will default to "Guest".
What are lifecycle methods in React class components?
Lifecycle methods are special methods in class components that allow developers to run code at specific points in a component's life (e.g., mounting, updating, and unmounting). Common lifecycle methods include:
componentDidMount()
: Called once after the component has been rendered in the DOM. Often used for data fetching or setting up subscriptions.componentDidUpdate()
: Called after the component has been updated. Used for responding to prop or state changes.componentWillUnmount()
: Called right before the component is removed from the DOM. Used for cleanup tasks such as canceling network requests or removing event listeners.
Example of lifecycle methods:
class Clock extends React.Component {
componentDidMount() {
this.timerID = setInterval(() => this.tick(), 1000);
}
componentWillUnmount() {
clearInterval(this.timerID);
}
render() {
return <h1>Time: {this.state.time}</h1>;
}
}