React Basics
What is React?
React is a popular open-source JavaScript library used for building user interfaces, particularly single-page applications. It allows developers to create reusable UI components, manage application state efficiently, and handle dynamic data updates. React is often used in combination with other libraries or frameworks to build complex web applications.
What are components in React?
Components are the building blocks of a React application. They allow developers to break down the UI into independent, reusable pieces. A React component can be a class component or a functional component, and each component manages its own state and renders a portion of the UI.
Example of a functional component:
function HelloWorld() {
return Hello, World!;
}
What is JSX in React?
JSX (JavaScript XML) is a syntax extension for JavaScript used in React. It allows developers to write HTML-like code within JavaScript, making it easier to define and structure the UI. JSX is not mandatory in React, but it simplifies creating components and visual layouts.
Example of JSX:
const element = <h1>Hello, JSX!</h1>;
Under the hood, JSX gets compiled into JavaScript function calls like React.createElement()
.
What is the difference between state and props in React?
State and props are both used to manage data in React components, but they serve different purposes:
- State: Represents the component's internal data and can be changed over time, triggering a re-render when updated.
- Props: Short for "properties," they are read-only inputs passed from a parent component to a child component. Props are immutable and cannot be changed by the receiving component.
Example of props:
function Greeting(props) {
return <h1>Hello, {props.name}!</h1>;
}
<Greeting name="Alice" />
What is the Virtual DOM in React?
The Virtual DOM is a lightweight representation of the actual DOM in memory. When the state of a React component changes, React creates a new Virtual DOM tree, compares it with the previous version (diffing), and updates only the parts of the actual DOM that changed. This process improves performance by minimizing expensive DOM manipulations.
What is the role of keys in React lists?
Keys are unique identifiers that React uses to track individual elements in a list. They help React efficiently update and re-render elements by associating changes with the correct elements. Each key should be unique among sibling elements to prevent rendering issues.
Example of using keys in a list:
const items = ['Apple', 'Banana', 'Cherry'];
function FruitList() {
return (
<ul>
{items.map((item, index) => (
<li key={index}>{item}</li>
))}
</ul>
);
}
What is the use of useState in React?
useState
is a hook in React that allows functional components to manage local state. It returns an array containing the current state value and a function to update that state.
Example of using 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>
);
}
What is the purpose of useEffect
in React?
useEffect
is a hook used to perform side effects in functional components, such as fetching data, updating the DOM, or setting up event listeners. It runs after the component renders, and can also clean up effects when the component unmounts.
Example of using useEffect
:
import React, { useState, useEffect } from 'react';
function DataFetcher() {
const [data, setData] = useState(null);
useEffect(() => {
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => setData(data));
}, []);
return <div>Data: {JSON.stringify(data)}</div>;
}
What is the difference between a controlled and uncontrolled component in React?
A controlled component is a form element (e.g., input, textarea) whose value is controlled by the React state. The form element is updated by using an onChange
handler, and the input value is stored in state. An uncontrolled component manages its own state using the DOM, and the form data is accessed through ref
.
Example of a controlled component:
function ControlledInput() {
const [value, setValue] = useState("");
return (
<input
type="text"
value={value}
onChange={(e) => setValue(e.target.value)}
/>
);
}
Example of an uncontrolled component:
function UncontrolledInput() {
const inputRef = React.useRef(null);
const handleSubmit = () => {
alert(inputRef.current.value);
};
return (
<div>
<input type="text" ref={inputRef} />
<button onClick={handleSubmit}>Submit</button>
</div>
);
}
What is the use of props.children
in React?
props.children
is a special prop in React that allows components to pass and render child elements. It is useful when creating wrapper components or higher-order components where you need to nest other components or elements inside.
Example of using props.children
:
function Wrapper(props) {
return <div className="wrapper">{props.children}</div>;
}
function App() {
return (
<Wrapper>
<h1>This is a child element.</h1>
</Wrapper>
);
}
What is the difference between React and ReactDOM?
React is the core library responsible for managing UI components and the application state, while ReactDOM is responsible for rendering the components to the actual DOM. ReactDOM provides methods like ReactDOM.render()
to render React elements into the browser's DOM.
Example of using ReactDOM:
import React from 'react';
import ReactDOM from 'react-dom';
function App() {
return <h1>Hello, React!</h1>;
}
ReactDOM.render(<App />, document.getElementById('root'));