React 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
The virtual DOM is a lightweight copy of the real DOM. React uses the virtual DOM to make updates efficiently by only re-rendering the components that have changed.
One-way data binding means that data flows in a single direction,
from parent components to child components, ensuring predictable and easier-to-debug applications
React focuses on the view layer (UI), is unopinionated, and allows developers to integrate with other libraries for state management, routing, etc.
Angular and Vue are full-fledged frameworks that provide more out-of-the-box solutions.
No, JSX is not required. You can write React code without JSX using the React.createElement() method, but JSX is recommended because it simplifies writing and understanding code.
JSX looks like HTML but has differences, such as using className instead of class, and all JSX tags must be closed, even self-closing ones.
Yes, you can embed JavaScript expressions inside JSX using curly braces {}.
Example:{user.name}
You can render multiple elements by wrapping them in a single parent element, like a
Components are the building blocks of React applications.
They can be functional or class-based, and they allow you to split the UI into reusable, independent pieces.
Functional components are simple JavaScript functions that accept props and return JSX.
Class components are ES6 classes that extend React.Component and have access to lifecycle methods and state.
You pass data from a parent to a child component through props.
Example:.
Yes, components can return multiple elements by wrapping them in a React fragment (<> >), avoiding extra DOM nodes.
In a functional component, you use the useState hook to create state.
In a class component, you define this.state inside the constructor.
State is an object that holds dynamic data that influences the rendering of a component. It allows React components to re-render when the data changes
You update state in a functional component using the useState hook, which returns the current state and a function to update it.
In functional components, event handlers are typically passed as functions to elements. In class components, you can bind them using .bind(this) or by using arrow functions.
CProps are read-only and passed from parent to child components. State is mutable and managed within a component to control its behavior.
You can prevent the default behavior of an event by calling event.preventDefault() in the event handler.
You render a list by using the .map() function to iterate over an array and return JSX for each item.
Example: {items.map(item =>
The key attribute helps React identify which items have changed, been added, or removed, allowing for efficient re-rendering of lists
You can render conditional content using JavaScript conditions such as ternary operators or if statements inside JSX.
Example: {isLoggedIn ?: }.
Yes, you can render components conditionally by using JavaScript expressions in JSX.
For example, you can display different components based on a condition
If two elements have the same key, React may not properly update the elements during rendering, leading to unexpected behavior.
You can debug React apps using the browser's Developer Tools, the React Developer Tools extension, and logging important data to the console with console.log().
React Developer Tools is a browser extension that allows you to inspect the React component tree, view props, state, and hooks, and debug issues related to rendering.
You can check the browser console for any warnings or errors related to React, such as missing key props in lists or incorrect prop types.
You can add console.log() statements inside lifecycle methods (or hooks in functional components) to track when and how a component's state or props change.
You can use the debugger statement in your code to pause execution in the browser's debugger and inspect the state, props, and other variables
A class-based component is a React component defined as an ES6 class that extends React.Component.
It has access to lifecycle methods and manages its own state.
Lifecycle methods are special methods in class components that are called at different stages of a component's life, such as componentDidMount(), componentDidUpdate(), and componentWillUnmount().
You set the initial state in the constructor of a class component.
Example: this.state = { count: 0 }
You update state using the setState() method.
Example: this.setState({ count: this.state.count + 1 }).
super() is used to call the constructor of the parent class (React.Component). It is required when you use this in the constructor.
You can make HTTP requests in React using libraries like axios or the built-in fetch() API.
Using fetch API Example: import React, { useEffect, useState } from 'react'; const FetchExample = () => { const [data, setData] = useState(null); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); useEffect(() => { // Make an HTTP GET request using fetch fetch('https://jsonplaceholder.typicode.com/posts/1') .then((response) => { if (!response.ok) { throw new Error('Network response was not ok'); } return response.json(); }) .then((data) => { setData(data); // Set the fetched data setLoading(false); // Turn off the loading state }) .catch((error) => { setError(error.message); // Handle any errors setLoading(false); }); }, []); // Empty dependency array ensures it runs once when the component mounts if (loading) returnLoading...
; if (error) returnError: {error}
; return (); }; export default FetchExample; Using Axios # First, install Axios npm install axios import React, { useEffect, useState } from 'react'; import axios from 'axios'; const AxiosExample = () => { const [data, setData] = useState(null); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); useEffect(() => { // Make an HTTP GET request using Axios axios.get('https://jsonplaceholder.typicode.com/posts/1') .then((response) => { setData(response.data); // Set the fetched data setLoading(false); // Turn off the loading state }) .catch((error) => { setError(error.message); // Handle any errors setLoading(false); }); }, []); // Empty dependency array ensures it runs once when the component mounts if (loading) return{data.title}
{data.body}
Loading...
; if (error) returnError: {error}
; return (); }; export default AxiosExample;{data.title}
{data.body}
You can handle HTTP requests in functional components using the useEffect() hook to trigger the request when the component mounts
You handle errors in HTTP requests by using .catch() for promises (in fetch() or axios) and showing appropriate error messages in the UI.
You can send data to a server using a POST request with fetch() or axios.
Example: axios.post('/api/data', { key: value }).
Optimizations include caching data, debouncing frequent requests, and using tools like React Query to manage server state.
Custom hooks are reusable functions that contain logic using React hooks (useState, useEffect, etc.) and can be shared across different components.
You create a custom hook by defining a function that uses one or more of React's built-in hooks and returns some value.
Custom hooks must follow the naming convention use[CustomHookName].
The naming convention for custom hooks is that their name must begin with "use". This is required to follow React’s rules of hooks..
Custom hooks allow you to extract and share common logic (like fetching data or handling forms) between different components, improving code reusability.
Yes, a custom hook can call another custom hook. This allows for even greater abstraction and reusability of logic.
You handle form inputs by setting up controlled components, where the value of the input is tied to the component's state, and changes are handled by an onChange event handler.
Controlled components have their input values controlled by React state, while uncontrolled components rely on the DOM to manage the form data using ref.
You prevent the default form submission behavior by calling event.preventDefault() in the form's onSubmit handler.
You manage multiple form inputs by setting up a single onChange handler that updates the state for each input based on its name attribute
Form validation can be handled manually by checking state values before submission, or by using third-party libraries like Formik or React Hook Form to simplify the process
React Router is a library for managing navigation and routing in React applications.
It allows you to create single-page applications with multiple views without reloading the page.
You set up basic routing by wrapping your app in BrowserRouter and defining routes using Route components within a Switch or Routes component.
You can navigate between routes programmatically using the useNavigate hook in React Router v6 or useHistory in v5.
Dynamic routing is handled by defining routes with path parameters, such as /user/:id, and accessing the parameter using the useParams hook.
Link is used for basic navigation, while NavLink adds styling based on whether the link is active or not, making it ideal for navigation bars.
Authentication in React can be implemented using JWT (JSON Web Tokens), session management, or OAuth services by managing tokens in localStorage, sessionStorage, or cookies.
You can protect routes by creating a higher-order component (HOC) or using the Pr60ivateRoute component to check if the user is authenticated before rendering a route
User sessions can be managed by storing tokens (like JWT) in localStorage or cookies and verifying the token on every request or route change
useContext provides a way to pass authentication state down the component tree, while useReducer helps manage complex state logic, like logging in and logging out.
Token expiration can be handled by setting a timeout to log the user out when the token expires or by intercepting HTTP requests to check if the token is still valid.
>You can deploy a React app to services like Netlify or Vercel by linking your GitHub repository to the service and following their deployment steps.
Development builds contain full error messages, warnings, and hot reloading for debugging, while production builds are optimized and minified for better performance.
You create a production build using the command npm run build, which generates optimized files in the build folder that can be deployed to a web server
You configure your web server (e.g., Nginx, Apache) to serve the React app's index.html file for all routes to ensure the app works correctly with React Router.
Optimizations include using code splitting with React.lazy, minimizing bundle size with tree shaking, and serving compressed files (like Gzip or Brotli) from the server.