Explore the fundamentals of React with our collection of essential beginner-level questions.
Deepen your React knowledge with our advanced questions that cover state management and cross-platform compatibility.
Master React with our expert-level questions that delve into performance optimization and the inner workings of the React bridge.
Answer: ReactJS is a JavaScript library for building user interfaces, especially for single-page applications. It allows developers to create reusable UI components and manage the application's state efficiently. Main features include: - Virtual DOM for fast rendering - Component-based architecture - Unidirectional data flow - Support for server-side rendering
Answer: Components are the building blocks of a React application. They are JavaScript functions or classes that return React elements, which describe what you see on the screen. Differences: - Components can have state and lifecycle methods. - Elements are immutable descriptions of what you want to render. Think of components as blueprints and elements as the actual objects created from those blueprints.
Answer: JSX is a syntax extension for JavaScript that looks similar to HTML. It allows you to write HTML-like code within JavaScript, making it easier to create and visualize UI components. JSX is used in React because: - It combines JavaScript logic with markup. - It improves readability and maintainability by allowing UI elements and logic to be written in a single file. Example: ```jsx const element = <h1>Hello, world!</h1>; ```
Answer: The virtual DOM is an in-memory representation of the actual DOM. React uses the virtual DOM to efficiently update the UI. When the state of a component changes: 1. React creates a new virtual DOM. 2. It compares it with the previous version. 3. React calculates the minimal set of changes required to update the real DOM. This process is called reconciliation and improves performance by reducing direct DOM manipulations.
Answer: Class Components: - Are ES6 classes that extend React.Component. - Can have lifecycle methods and manage state. - Use 'this' to refer to component properties. Functional Components: - Are simple JavaScript functions. - Can use hooks like useState and useEffect for state management. - Are preferred for their simplicity and ability to use hooks. Example of a Functional Component: ```jsx function Welcome(props) { return <h1>Hello, {props.name}</h1>; } ``` Example of a Class Component: ```jsx class Welcome extends React.Component { render() { return <h1>Hello, {this.props.name}</h1>; } } ```
Answer: Props (short for properties) are used to pass data from parent to child components in React. They are read-only and cannot be modified by the child component. State is used to manage data that changes over time within a component. It is mutable and can be updated using the setState method in class components or the useState hook in functional components. Differences: - Props: Used to pass data between components. - State: Used to manage data within a component.
Answer: The render() method is used in class components to return the React elements that represent the UI. It is a required method in class components and is called whenever the component's state or props change, triggering a re-render of the component. The render method should be pure, meaning it should not modify the component's state or interact with external systems.
Answer: The component lifecycle in React consists of three main phases: 1. **Mounting**: When a component is created and inserted into the DOM. - Lifecycle methods: componentDidMount 2. **Updating**: When a component's props or state change. - Lifecycle methods: componentDidUpdate 3. **Unmounting**: When a component is removed from the DOM. - Lifecycle methods: componentWillUnmount
Answer: Keys are unique identifiers used by React to track changes in a list of elements. They help React identify which items have changed, been added, or been removed, optimizing the rendering process. Using keys improves performance by allowing React to update only the necessary elements in the DOM. Keys should be stable, predictable, and unique to each element in the list. Example: ```jsx const listItems = numbers.map((number) => <li key={number.toString()}>{number}</li> ); ```
Answer: useState is a hook in React that allows functional components to have state. It returns an array with two elements: the current state value and a function to update the state. By using useState, functional components can manage local state, making them more powerful and similar in capability to class components, but with simpler syntax. Example: ```jsx const [count, setCount] = useState(0); return ( <div> <p>You clicked {count} times</p> <button onClick={() => setCount(count + 1)}> Click me </button> </div> ); ```
Answer: useEffect is a hook in React that allows you to perform side effects in functional components. It is similar to lifecycle methods in class components, such as componentDidMount, componentDidUpdate, and componentWillUnmount. useEffect runs after the render and can be used for: - Fetching data - Directly updating the DOM - Setting up subscriptions or timers It accepts two arguments: a function containing the side-effect logic and an optional array of dependencies that determine when the effect should run. Example: ```jsx useEffect(() => { // Run this effect when the component mounts console.log('Component mounted'); return () => { // Cleanup when the component unmounts console.log('Component unmounted'); }; }, []); // Empty array means this effect runs once when mounted ```
Answer: In React, you can conditionally render components using: 1. **Ternary Operators**: Use a ternary expression to render a component based on a condition. ```jsx {isLoggedIn ? <Dashboard /> : <Login />} ``` 2. **Logical && Operator**: Use the && operator to render a component only if a condition is true. ```jsx {isLoggedIn && <Dashboard />} ``` 3. **if-else Statements**: Use traditional if-else logic to return different components. ```jsx if (isLoggedIn) { return <Dashboard />; } else { return <Login />; } ```
Answer: React Router is a library for routing in React applications. It enables navigation between different components and pages without reloading the entire application. React Router provides: - Declarative routing using components like <Route> and <Link>. - Nested routing to build complex interfaces. - Dynamic routing based on URL parameters. Example usage: ```jsx import { BrowserRouter as Router, Route, Link } from 'react-router-dom'; function App() { return ( <Router> <div> <Link to="/">Home</Link> <Link to="/about">About</Link> <Route path="/" exact component={Home} /> <Route path="/about" component={About} /> </div> </Router> ); } ```
Answer: Higher-order components (HOCs) are functions that take a component and return a new component. HOCs are used to add additional functionality to existing components without modifying them directly. They allow for code reuse, logic sharing, and abstraction. Example of a HOC that adds logging functionality: ```jsx function withLogging(WrappedComponent) { return class extends React.Component { componentDidMount() { console.log('Component mounted'); } render() { return <WrappedComponent {...this.props} />; } }; } const EnhancedComponent = withLogging(MyComponent); ```
Answer: useContext is a hook in React that allows functional components to access context values. It provides a way to share data between components without passing props through every level of the component tree. useContext simplifies accessing context data and makes components easier to read and maintain. Example: ```jsx const ThemeContext = React.createContext('light'); function ThemeButton() { const theme = useContext(ThemeContext); return <button className={theme}>Click me</button>; } ```
Answer: Handling forms in React involves managing input values, handling user input, and submitting form data. Steps to handle forms: 1. Set up state to store input values using useState. 2. Create input fields and bind them to the state. 3. Handle input changes using onChange events. 4. Submit the form using an onSubmit handler. Example: ```jsx function MyForm() { const [name, setName] = useState(''); const handleSubmit = (event) => { event.preventDefault(); console.log('Submitted name:', name); }; return ( <form onSubmit={handleSubmit}> <input type="text" value={name} onChange={(e) => setName(e.target.value)} /> <button type="submit">Submit</button> </form> ); } ```
Answer: Fragments are used to group a list of children elements without adding extra nodes to the DOM. They are useful for returning multiple elements from a component without adding an unnecessary wrapper element. Fragments can be used with the <React.Fragment> tag or the shorthand <> syntax. Example: ```jsx function MyComponent() { return ( <> <h1>Title</h1> <p>This is a paragraph.</p> </> ); } ```
Answer: shouldComponentUpdate is a lifecycle method in class components that allows you to control when a component should re-render. It is used to improve performance by preventing unnecessary re-renders. This method is called before rendering when new props or state are received. You can return false if you want to prevent the re-render, and true if you want to allow it. Example: ```jsx class MyComponent extends React.Component { shouldComponentUpdate(nextProps, nextState) { // Only re-render if the new props or state are different return nextProps.value !== this.props.value; } render() { return <div>{this.props.value}</div>; } } ```
Answer: Optimizing React application performance can be achieved through various techniques: - **Use Production Build**: Make sure to use the production build for deployment, which includes optimizations. - **Code Splitting**: Use React.lazy and Suspense to load components lazily, reducing the initial bundle size. - **Memoization**: Use React.memo and useMemo to prevent unnecessary re-renders of components and calculations. - **Optimize State Management**: Keep the component state local where necessary and avoid redundant state updates. - **Use Pure Components**: Use PureComponent or React.memo to automatically prevent re-renders when props or state have not changed. - **Avoid Inline Functions**: Declare functions outside of render methods to avoid creating new functions on each render.
Answer: Prop drilling is the process of passing data through multiple layers of components to reach a deeply nested component. It can make components difficult to manage and understand. Ways to avoid prop drilling: - **Context API**: Use React's Context API to share data globally without passing props through every component. - **State Management Libraries**: Use libraries like Redux or MobX to manage global state. Example using Context API: ```jsx const MyContext = React.createContext(); function Parent() { return ( <MyContext.Provider value="shared data"> <Child /> </MyContext.Provider> ); } function Child() { const value = useContext(MyContext); return <div>{value}</div>; } ```