ReactJSQNA4ExperiencedSet1
ReactJS Q and A 4 Experienced Set 1
- What
are React Hooks? Explain their use cases.
React Hooks are functions that allow you to use state and
other React features in functional components. Common hooks include useState,
useEffect, useContext, and useReducer. They were
introduced in React 16.8.
Example:
import React, { useState, useEffect } from 'react'; function
ExampleComponent() { const [count, setCount] = useState(0); useEffect(() =>
{ document.title = `Count: ${count}`; }, [count]); return ( <div> <p>Count:
{count}</p> <button onClick={() => setCount(count +
1)}>Increment</button> </div> ); }
- What
is the virtual DOM in React, and how does it work?
The virtual DOM is a lightweight in-memory representation of
the actual DOM. React uses it to improve performance by minimizing direct
manipulation of the real DOM. When the state of a component changes, React
creates a new virtual DOM tree, compares it with the previous one, and
calculates the minimal set of changes needed to update the real DOM.
- Explain
React Router and its usage. Provide an example.
React Router is a popular library for handling routing in
React applications. It allows you to define routes and their corresponding
components, enabling client-side navigation.
Example:
import React from 'react'; import { BrowserRouter as Router,
Route, Link } from 'react-router-dom'; function App() { return ( <Router>
<div> <nav> <ul> <li><Link to="/">Home</Link></li>
<li><Link to="/about">About</Link></li> <li><Link
to="/contact">Contact</Link></li> </ul> </nav>
<Route path="/" exact component={Home} /> <Route path="/about"
component={About} /> <Route path="/contact" component={Contact}
/> </div> </Router> ); }
- What
is Redux, and how does it differ from React's built-in state management?
Redux is a state management library for React applications.
It provides a centralized store to manage application state and allows
predictable state updates using actions and reducers. Redux is suitable for
complex applications with extensive state-sharing requirements, whereas React's
built-in state management is ideal for simpler scenarios.
- Explain
the concept of controlled and uncontrolled components in React forms.
Provide examples.
Controlled components are React components where form
elements (like input fields) have their values controlled by React state.
Uncontrolled components are those where the form elements manage their state
independently.
Example of a controlled component:
import React, { useState } from 'react'; function ControlledInput()
{ const [value, setValue] = useState(''); const handleChange = (e) => { setValue(e.target.value);
}; return ( <input type="text" value={value} onChange={handleChange}
/> ); }
Example of an uncontrolled component:
function UncontrolledInput() { let inputRef = React.createRef();
const handleButtonClick = () => { alert(`Input value: ${inputRef.current.value}`);
}; return ( <div> <input type="text" ref={inputRef} /> <button
onClick={handleButtonClick}>Get Value</button> </div> ); }
- What
is the significance of the key prop in React lists, and why is it
important?
The key prop is used to uniquely identify elements in
a list of React components. It helps React efficiently update and re-render
components when the list changes. Each key should be unique among its siblings
in the list.
Example:
function TodoList({ todos }) { return ( <ul>
{todos.map((todo) => ( <li key={todo.id}>{todo.text}</li> ))} </ul>
); }
- Explain
how to handle forms in React and discuss form validation techniques.
To handle forms in React, you can create controlled
components for each form input and update state as the user interacts with the
form. Form validation can be done using conditional rendering or libraries like
Formik and Yup.
Example of form handling:
import React, { useState } from 'react'; function LoginForm()
{ const [formData, setFormData] = useState({ username: '', password: '' }); const
handleChange = (e) => { setFormData({ ...formData, [e.target.name]: e.target.value
}); }; const handleSubmit = (e) => { e.preventDefault(); // Perform form
submission logic with formData }; return ( <form onSubmit={handleSubmit}>
<input type="text" name="username" value={formData.username}
onChange={handleChange} /> <input type="password" name="password"
value={formData.password} onChange={handleChange} /> <button type="submit">Submit</button>
</form> ); }
- What
is the purpose of React context, and how can it be used to manage global
state?
React context is a mechanism for sharing state and passing
it down the component tree without prop drilling. It's useful for managing
global state, like user authentication, themes, or localization.
Example:
import React, { createContext, useContext, useState } from 'react';
const MyContext = createContext(); function App() { const [value, setValue] = useState('Hello
from Context'); return ( <MyContext.Provider value={value}> <ChildComponent
/> </MyContext.Provider> ); } function ChildComponent() { const
contextValue = useContext(MyContext); return <div>{contextValue}</div>;
}
- How
can you optimize performance in React applications?
Performance optimization in React can be achieved through
techniques like:
- Memoization
(using React.memo or custom shouldComponentUpdate)
- Code-splitting
with dynamic imports
- Lazy
loading of components
- Efficiently
using React's useEffect hook with proper dependency arrays
- Implementing
virtualized lists for large datasets
- Caching
API responses
- Explain
the concept of Higher-Order Components (HOCs) in React. Provide an
example.
HOCs are functions that take a component and return a new
component with additional props or behavior. They are used for code reuse, prop
manipulation, and abstracting common logic.
Example:
// A HOC that adds a "loading" prop to a component
function withLoading(Component) { return function WithLoading(props) { const
[isLoading, setLoading] = useState(true); useEffect(() => { // Simulate an
async operation setTimeout(() => { setLoading
- Explain
the concept of PureComponent in React. How does it differ from a regular
component?
PureComponent is a base class for React components
that performs a shallow comparison of the current and previous props and state.
If there are no changes, it prevents unnecessary renders. In contrast, regular
components re-render whenever their parent component renders, even if the props
or state remain the same.
- Discuss
the use of React Fragments. Why might you need them?
React Fragments (<>...</>) allow you to
group multiple elements without adding extra nodes to the DOM. They are
particularly useful when you need to return multiple elements from a
component's render method without wrapping them in a container element.
Example:
function MyComponent() { return ( <> <h1>Hello</h1>
<p>World</p> </> ); }
- What
is the purpose of the dangerouslySetInnerHTML attribute in React, and when
should it be used?
dangerouslySetInnerHTML is used to set HTML directly
into a component. It should be used sparingly and only when you trust the
source of the HTML content, such as when rendering user-generated content or
integrating with third-party libraries that produce HTML.
Example:
function RenderHTML() { const htmlContent = '<div><p>This
is HTML content.</p></div>'; return <div dangerouslySetInnerHTML={{
__html: htmlContent }} />; }
- Explain
how to handle events in React and the differences between synthetic events
and native events.
In React, you can handle events like onClick or onChange
by providing event handler functions. React uses a synthetic event system that
normalizes browser inconsistencies. Unlike native events, synthetic events are
reused and have the same API across all browsers.
Example:
function MyButton() { const handleClick = () => { alert('Button
clicked'); }; return <button onClick={handleClick}>Click me</button>;
}
- What
are the key differences between useState and useReducer in React, and when
should you use one over the other?
Both useState and useReducer are used for
managing state in functional components. useState is simpler and
suitable for managing independent state variables, while useReducer is
more powerful and useful for complex state updates, especially when you have
multiple related state variables.
- Explain
the concept of the Context API in React. When is it preferable to use a
state management library like Redux instead?
The Context API allows you to pass data through the
component tree without prop drilling. It's useful for moderate state sharing
between components. However, for large and complex applications with advanced
state management requirements, Redux or similar libraries provide better tools
for managing application-wide state and actions.
- What
is server-side rendering (SSR) in React, and why might you use it?
Server-side rendering involves rendering React components on
the server instead of the client. SSR can improve initial page load times and
SEO. It's suitable for applications where search engine optimization and fast
initial rendering are critical.
- Explain
the concept of code splitting in React and how it can be achieved.
Code splitting is a technique to load only the JavaScript
code needed for the current view, reducing the initial bundle size. It can be
achieved using dynamic imports and tools like Webpack's import()
function.
Example:
import React, { lazy, Suspense } from 'react'; const LazyComponent
= lazy(() => import('./LazyComponent')); function App() { return ( <Suspense
fallback={<div>Loading...</div>}> <LazyComponent /> </Suspense>
); }
- How
can you handle authentication and authorization in a React application?
Authentication and authorization can be handled using
various techniques, including using tokens (JWTs), OAuth, or integrating with
authentication libraries like Firebase or Auth0. Authorization can be managed
by checking user roles and permissions before rendering specific components or
routes.
- Explain
the concept of error boundaries in React and how to use them to handle
errors gracefully.
Error boundaries are special React components that catch
JavaScript errors in their child component tree, log them, and display a
fallback UI. They help prevent the entire application from crashing due to a
single error.
Example:
class ErrorBoundary extends React.Component { constructor(props)
{ super(props); this.state = { hasError: false }; } componentDidCatch(error,
errorInfo) { this.setState({ hasError: true }); // Log or report the error } render()
{ if (this.state.hasError) { return <div>Something went wrong.</div>;
} return this.props.children; } }
- Explain
the concept of React portals. When and why should you use them?
React portals allow you to render a component's children
into a DOM node that exists outside the parent component's DOM hierarchy. This
is useful for scenarios like modals, tooltips, and overlays where you need to
render content outside the current component's position in the DOM.
Example:
import React from 'react'; import ReactDOM from 'react-dom';
function Modal({ children }) { return ReactDOM.createPortal( children, document.getElementById('modal-root')
); }
- Discuss
the significance of the shouldComponentUpdate method in React class
components. How can it be used to optimize rendering?
shouldComponentUpdate is a lifecycle method in class
components that allows you to control when a component should re-render. By
implementing this method, you can prevent unnecessary renders and optimize
performance by specifying conditions under which a component should update.
Example:
class MyComponent extends React.Component { shouldComponentUpdate(nextProps,
nextState) { // Return true to allow re-render, or false to prevent it based on
conditions return this.props.someProp !== nextProps.someProp; } render() { //
Component rendering logic } }
- Explain
the concept of React hooks rules, particularly the "Don't call Hooks
inside loops, conditions, or nested functions" rule. Why is it
important to follow this rule?
React hooks should be called at the top level of a functional
component and not inside loops, conditions, or nested functions. This ensures
that hooks are called consistently on every render and helps React track their
state correctly. Violating this rule can lead to unexpected behavior and bugs.
Example:
// Don't do this function MyComponent() { if (condition) { useState();
// Incorrect usage inside a condition } // ... }
- Explain
the concept of Redux Thunk middleware and how it is used for handling
asynchronous actions in Redux. Provide an example.
Redux Thunk is a middleware that allows you to dispatch
functions (thunks) instead of plain actions. It's commonly used for handling
asynchronous actions, such as making API calls, in Redux.
Example:
// Redux Thunk action creator const fetchUserData = (userId)
=> { return async (dispatch) => { try { const response = await fetch(`/api/users/${userId}`);
const data = await response.json(); dispatch({ type: 'FETCH_USER_SUCCESS', payload:
data }); } catch (error) { dispatch({ type: 'FETCH_USER_FAILURE', payload:
error.message }); } }; };
- What
is the significance of the key prop in React lists, and why is it
important to provide a stable and unique key for each list item?
The key prop in React lists is used by React's
reconciliation algorithm to uniquely identify and track elements during
updates. Providing stable and unique keys helps React efficiently update and
re-render list items without unnecessary re-renders or bugs.
Example:
function TodoList({ todos }) { return ( <ul>
{todos.map((todo) => ( <li key={todo.id}>{todo.text}</li> ))} </ul>
); }
- What
is React Fiber, and how does it improve the performance of React
applications?
React Fiber is an internal rewrite of React's core
algorithm. It allows React to work on chunks of work (fiber) and prioritize
rendering updates, making it more responsive and capable of handling complex
user interfaces without blocking the main thread. Fiber improves performance by
enabling asynchronous rendering and concurrent updates.
- Explain
the concept of Higher-Order Components (HOCs) and how they can be used for
code reuse in React applications. Provide an example.
Higher-Order Components (HOCs) are functions that take a
component and return a new component with additional props or behavior. They
are a way to reuse component logic without changing the component's structure.
Example:
// A HOC that adds a "theme" prop to a component function
withTheme(Component) { return function ThemedComponent(props) { return <Component
{...props} theme="dark" />; }; }
- Discuss
the concept of memoization in React and how the React.memo higher-order
component is used to optimize rendering. Provide an example.
Memoization is a technique that caches the result of a
function call based on its input and reuses it when the same input is
encountered again. React.memo is a higher-order component that memoizes
a functional component to prevent re-rendering unless its props change.
Example:
const MemoizedComponent = React.memo(function MyComponent(props)
{ // Component rendering logic });
- What
is the purpose of the useEffect hook in React, and how does it help manage
side effects? Provide examples of common use cases.
The useEffect hook in React is used to manage side
effects in functional components. It allows you to perform tasks like data
fetching, DOM manipulation, and subscription handling. It accepts a function
that runs after rendering and can be used to clean up effects as well.
Example of data fetching:
useEffect(() => { fetch('/api/data') .then((response)
=> response.json()) .then((data) => { // Update state with fetched data
}); }, []); // Empty dependency array means this effect runs once on mount
- Explain
the concept of React memoization using the useMemo hook. When and why
should you use it?
React's useMemo hook allows you to memoize expensive
calculations, preventing them from being recalculated on every render. It's
useful when you have a calculation that depends on specific props or state and
doesn't need to be recalculated unless those dependencies change.
Example:
const MemoizedComponent = () => { const
expensiveCalculation = useMemo(() => { // Calculate something based on props
or state return props.someValue * 2; }, [props.someValue]); return <div>Result:
{expensiveCalculation}</div>; };
- What
are React fragments, and how do they differ from regular HTML elements?
Provide examples of when to use fragments.
React fragments, represented as <>...</>,
are lightweight wrappers that allow you to group multiple elements without
adding an extra DOM node. They don't introduce any additional elements when
rendered and are useful when you want to return adjacent JSX elements without a
parent container.
Example:
function ExampleComponent() { return ( <> <h1>Title</h1>
<p>Paragraph 1</p> <p>Paragraph 2</p> </> ); }
- Discuss
the concept of the React Strict Mode. How does it help in identifying and
fixing potential problems in React applications?
React Strict Mode is a development mode that helps you
identify and address potential problems in your application. It performs
additional checks and warnings during rendering, highlighting issues like
unsafe lifecycle methods and unexpected side-effects. It's particularly helpful
for catching and fixing problems early in development.
To enable Strict Mode, wrap your root component in <React.StrictMode>
in your app's entry point.
- What
are controlled and uncontrolled components in React forms? Provide examples
and explain when to use each.
Controlled components are those where form element values
are controlled by React state. Uncontrolled components are those where form
elements manage their state independently.
Example of a controlled component:
function ControlledInput() { const [value, setValue] = useState('');
const handleChange = (e) => { setValue(e.target.value); }; return <input type="text"
value={value} onChange={handleChange} />; }
Example of an uncontrolled component:
function UncontrolledInput() { const inputRef = useRef(); const
handleButtonClick = () => { alert(`Input value: ${inputRef.current.value}`);
}; return ( <div> <input type="text" ref={inputRef} /> <button
onClick={handleButtonClick}>Get Value</button> </div> ); }
- Explain
the purpose and usage of the useRef hook in React. Provide an example of
when and why you might use it.
The useRef hook allows you to create a mutable ref
object that persists across renders. It is often used to access and interact
with DOM elements, manage focus, or store values that do not trigger
re-renders.
Example of accessing a DOM element:
function MyComponent() { const inputRef = useRef(); const focusInput
= () => { inputRef.current.focus(); }; return ( <> <input ref={inputRef}
/> <button onClick={focusInput}>Focus Input</button> </>
); }
- What
is the significance of React's forwardRef function, and how is it used for
passing refs to child components? Provide an example.
forwardRef is a function that allows you to pass a
ref from a parent component to a child component that doesn't create a DOM
element. It is commonly used for managing focus or accessing child component
methods and properties.
Example:
const MyInput = React.forwardRef((props, ref) => { return
<input ref={ref} />; }); function ParentComponent() { const inputRef = useRef();
const focusInput = () => { inputRef.current.focus(); }; return ( <> <MyInput
ref={inputRef} /> <button onClick={focusInput}>Focus Input</button>
</> ); }
- Discuss
the concept of the React Context API and how it helps in managing global
state. Provide examples of when and why you might use it.
The React Context API allows you to share data and state
across the component tree without prop drilling. It's useful for managing
global state, such as user authentication, themes, or localization, and
simplifies the passing of data between deeply nested components.
Example of managing theme:
const ThemeContext = React.createContext('light'); function App()
{ return ( <ThemeContext.Provider value="dark"> <ThemedComponent
/> </ThemeContext.Provider> ); } function ThemedComponent() { const
theme = useContext(ThemeContext); return <div>Theme: {theme}</div>;
}
- Explain
the concept of React Portals and provide examples of when and how you
might use them.
React Portals allow you to render components outside their
parent DOM hierarchy. This is useful for scenarios like modals, tooltips, and
overlays where you want to render content in a different part of the DOM.
Example of rendering a modal outside the root:
function Modal({ children }) { return ReactDOM.createPortal(children,
document.getElementById('modal-root')); } function App() { return ( <> <h1>Main
App Content</h1> <Modal> <p>Modal Content</p> </Modal>
</> ); }
- What
is the purpose of the dangerouslySetInnerHTML prop in React, and why
should you use it with caution? Provide an example.
dangerouslySetInnerHTML is a prop that allows you to
set HTML content inside a React component. It should be used cautiously because
it can potentially expose your application to cross-site scripting (XSS)
attacks if the HTML content is not trusted.
Example:
function RenderHTML() { const htmlContent = '<div><p>This
is HTML content.</p></div>'; return <div dangerouslySetInnerHTML={{
__html: htmlContent }} />; }
- What
is the purpose of the React.Fragment component in React, and how does it
differ from using empty angle brackets (<>...</>) as a
fragment?
React.Fragment is a built-in component in React used
to group multiple elements without introducing an additional DOM element. It
serves the same purpose as the empty angle brackets (<>...</>),
but it can be more explicitly named, making your code more readable and maintainable.
Example:
function MyComponent() { return ( <React.Fragment> <h1>Title</h1>
<p>Paragraph 1</p> <p>Paragraph 2</p> </React.Fragment>
); }
- Explain
the concept of React Router's BrowserRouter and HashRouter components.
When would you use one over the other, and why?
BrowserRouter and HashRouter are both
components provided by React Router for handling client-side routing. BrowserRouter
uses the browser's history API to manage URLs, while HashRouter uses the
URL hash. You would typically use BrowserRouter in a production
environment with server configuration, while HashRouter is often used
for simpler setups or when server configuration is not an option.
Example using BrowserRouter:
import { BrowserRouter as Router, Route, Link } from 'react-router-dom';
function App() { return ( <Router> <nav> <ul> <li><Link
to="/">Home</Link></li> <li><Link to="/about">About</Link></li>
</ul> </nav> <Route path="/" exact component={Home}
/> <Route path="/about" component={About} /> </Router>
); }
- Explain
how to conditionally render components in React. Provide examples with
different conditional rendering approaches.
Conditional rendering in React involves rendering different
components or content based on specific conditions or state. You can use if
statements, ternary operators, or logical && and ||
operators for this purpose.
Example with ternary operator:
function MyComponent({ isLoggedIn }) { return ( <div>
{isLoggedIn ? <p>Welcome, User!</p> : <p>Please log in.</p>}
</div> ); }
- What
is the significance of the key prop in React lists, and why should keys be
unique among siblings? How can you handle situations where keys might not
be unique?
The key prop in React lists is used to help React
identify each element uniquely and efficiently update the DOM. Keys should be
unique among siblings to ensure React can correctly reconcile and update the
components. In situations where you can't guarantee unique keys, consider using
a combination of unique identifiers or library-generated keys.
Example with library-generated keys (using uuid
library):
import { v4 as uuidv4 } from 'uuid'; function TodoList({
todos }) { return ( <ul> {todos.map((todo) => ( <li key={uuidv4()}>{todo.text}</li>
))} </ul> ); }
- Explain
the concept of Redux middleware and provide an example of a middleware you
might use in a Redux application.
Redux middleware are functions that intercept and process
actions before they reach the reducer. They are useful for handling
asynchronous actions, logging, analytics, and more. A common middleware is redux-thunk,
which allows you to dispatch functions as actions.
Example using redux-thunk:
import { createStore, applyMiddleware } from 'redux'; import
thunk from 'redux-thunk'; const store = createStore(reducer, applyMiddleware(thunk));
const fetchUserData = (userId) => { return (dispatch) => { dispatch({ type:
'FETCH_USER_REQUEST' }); fetch(`/api/users/${userId}`) .then((response) =>
response.json()) .then((data) => { dispatch({ type: 'FETCH_USER_SUCCESS', payload:
data }); }) .catch((error) => { dispatch({ type: 'FETCH_USER_FAILURE', payload:
error }); }); }; };
- Discuss
the concept of React lazy loading and how it can be used to improve
application performance. Provide an example.
React lazy loading allows you to load components only when
they are needed, reducing the initial bundle size and improving performance.
It's particularly useful for code-splitting and loading components on-demand.
Example using dynamic import() for lazy loading:
const LazyComponent = React.lazy(() => import('./LazyComponent'));
function App() { return ( <React.Suspense fallback={<div>Loading...</div>}>
<LazyComponent /> </React.Suspense> ); }
- Explain
the concept of controlled and uncontrolled components in React forms, and
provide a use case for each.
Controlled components are those where the form element's
value is controlled by React state. Uncontrolled components are those where the
form element manages its own state. Use controlled components when you need to
have full control over form input values and perform validation. Uncontrolled
components may be suitable when integrating with non-React libraries or when
you want to minimize React state management.
Controlled component example (already covered):
function ControlledInput() { const [value, setValue] = useState('');
const handleChange = (e) => { setValue(e.target.value); }; return <input type="text"
value={value} onChange={handleChange} />; }
Uncontrolled component example (already covered):
function UncontrolledInput() { const inputRef = useRef(); const
handleButtonClick = () => { alert(`Input value: ${inputRef.current.value}`);
}; return ( <div> <input type="text" ref={inputRef} /> <button
onClick={handleButtonClick}>Get Value</button> </div> ); }
- Explain
the concept of React's error boundaries and how they help in handling
errors gracefully. Provide an example.
React error boundaries are components that catch JavaScript
errors during rendering, allowing you to handle them gracefully and display fallback
UI instead of a crashing application. They help isolate errors and prevent them
from affecting the entire component tree.
Example:
class ErrorBoundary extends React.Component { constructor(props)
{ super(props); this.state = { hasError: false }; } componentDidCatch(error,
errorInfo) { this.setState({ hasError: true }); // Log or report the error } render()
{ if (this.state.hasError) { return <div>Something went wrong.</div>;
} return this.props.children; } } <ErrorBoundary> <MyComponent />
</ErrorBoundary>
- What
is the purpose of the useLayoutEffect hook in React, and how does it
differ from useEffect? Provide an example of a use case for useLayoutEffect.
useLayoutEffect is similar to useEffect but
fires synchronously after all DOM mutations. It's useful when you need to
perform DOM measurements or synchronous actions that may affect layout
immediately after rendering.
Example of using useLayoutEffect for measuring an
element's size:
import { useState, useLayoutEffect, useRef } from 'react'; function
MeasureElementSize() { const [size, setSize] = useState({ width: 0, height: 0
}); const elementRef = useRef(null); useLayoutEffect(() => { const element =
elementRef.current; if (element) { const rect = element.getBoundingClientRect();
setSize({ width: rect.width, height: rect.height }); } }, []); return ( <div
ref={elementRef}> Element size: {size.width} x {size.height} </div> );
}
- What
are the key differences between React function components and class
components? Provide examples of when you might choose one over the other.
React function components are simpler and more concise
compared to class components. Function components use the useState and useEffect
hooks for managing state and side effects, while class components use this.state
and lifecycle methods.
Example of a function component:
function FunctionComponent() { const [count, setCount] = useState(0);
useEffect(() => { document.title = `Count: ${count}`; }, [count]); return ( <div>
<p>Count: {count}</p> <button onClick={() => setCount(count +
1)}>Increment</button> </div> ); }
Example of a class component (for comparison):
class ClassComponent extends React.Component { constructor(props)
{ super(props); this.state = { count: 0 }; } componentDidMount() { document.title
= `Count: ${this.state.count}`; } componentDidUpdate() { document.title = `Count:
${this.state.count}`; } render() { return ( <div> <p>Count:
{this.state.count}</p> <button onClick={() => this.setState({
count: this.state.count + 1 })}> Increment </button> </div> ); }
}
- Explain
the concept of the virtual DOM in React. How does it contribute to
improved performance?
The virtual DOM is a lightweight in-memory representation of
the actual DOM. React uses the virtual DOM to efficiently update and re-render
components. When a component's state changes, React creates a new virtual DOM
tree, compares it with the previous one, and calculates the minimal set of
changes required to update the actual DOM. This process reduces unnecessary DOM
manipulation, leading to improved performance.
- What
is the purpose of the useReducer hook in React, and how does it work?
Provide an example of when and why you might use it.
The useReducer hook is used for managing complex
state logic in functional components. It's similar to useState but more
suitable for situations where the next state depends on the previous state and
actions. It takes a reducer function and an initial state, and returns the
current state and a dispatch function to trigger actions.
Example:
const initialState = { count: 0 }; const reducer = (state,
action) => { switch (action.type) { case 'INCREMENT': return { count: state.count
+ 1 }; case 'DECREMENT': return { count: state.count - 1 }; default: return
state; } }; function Counter() { const [state, dispatch] = useReducer(reducer,
initialState); return ( <div> <p>Count: {state.count}</p> <button
onClick={() => dispatch({ type: 'INCREMENT' })}>Increment</button> <button
onClick={() => dispatch({ type: 'DECREMENT' })}>Decrement</button> </div>
); }
- Discuss
the concept of prop drilling in React. How can you mitigate or avoid prop
drilling when passing data between deeply nested components?
Prop drilling occurs when you pass data through multiple
levels of components in a component tree. To mitigate or avoid prop drilling,
you can use techniques like the Context API or state management libraries like
Redux to share data across components without explicitly passing props through
all intermediate components.
- What
is the difference between the React.memo and PureComponent optimizations
in React, and when should you use each?
React.memo is a higher-order component that memoizes
a functional component to prevent re-renders unless its props change. PureComponent
is a base class for class components that automatically perform a shallow
comparison of props and state to prevent re-renders.
Use React.memo for functional components and PureComponent
for class components when you want to optimize rendering and prevent
unnecessary updates.
Example using React.memo:
const MemoizedComponent = React.memo(function MyComponent(props)
{ // Component rendering logic });
Example using PureComponent:
class MyComponent extends React.PureComponent { // Component
rendering logic }
- Explain
the concept of React Hooks Rules. What are the common rules that should be
followed when using hooks?
React Hooks Rules are guidelines for using hooks correctly.
Common rules include:
- Hooks
should be called at the top level of functional components, not inside
loops, conditions, or nested functions.
- Hooks
should have the same order on every render.
- Custom
hooks should start with "use" to indicate their purpose.
- Don't
call hooks from regular JavaScript functions or class components.
- What
is the purpose of the useContext hook in React, and how does it work?
Provide an example of how to use it.
The useContext hook is used to access the value of a
context created with React.createContext. It allows components to
consume context values without having to pass props through all intermediate
components.
Example:
const ThemeContext = React.createContext('light'); function ThemedComponent()
{ const theme = useContext(ThemeContext); return <div>Theme: {theme}</div>;
}
- Explain
the concept of code splitting in React and how it can be achieved. What
are the benefits of code splitting?
Code splitting is a technique to split a JavaScript bundle
into smaller chunks that can be loaded on-demand. It's achieved using dynamic
imports or tools like Webpack's import() function. The benefits of code
splitting include faster initial page load times, reduced bundle sizes, and
improved performance.
Example using dynamic import():
import React, { lazy, Suspense } from 'react'; const LazyComponent
= lazy(() => import('./LazyComponent')); function App() { return ( <Suspense
fallback={<div>Loading...</div>}> <LazyComponent /> </Suspense>
); }
- Explain
the concept of server-side rendering (SSR) in React. What are the
advantages and disadvantages of using SSR in a React application?
Server-side rendering (SSR) is a technique where React
components are rendered on the server instead of the client. Advantages of SSR
include improved SEO, faster initial loading, and better perceived performance.
Disadvantages may include increased server load and complexity.
- How
can you prevent cross-site scripting (XSS) attacks in a React application?
Provide examples of best practices to mitigate XSS vulnerabilities.
To prevent XSS attacks in a React application, follow best
practices like:
- Using
the dangerouslySetInnerHTML prop only with trusted content.
- Avoiding
string interpolation when rendering dynamic data.
- Using
libraries for sanitizing user-generated content.
- Setting
the Content Security Policy (CSP) header to restrict unsafe
scripts.
Example of safe usage of dangerouslySetInnerHTML:
function SafeHTML({ htmlContent }) { const sanitizedHTML = sanitizeHTML(htmlContent);
// Use a trusted library for sanitization return <div dangerouslySetInnerHTML={{
__html: sanitizedHTML }} />; }
- Explain
the concept of React hooks rules, particularly the "Don't call Hooks
inside loops, conditions, or nested functions" rule. Why is it
important to follow this rule?
React hooks, such as useState and useEffect,
should be called at the top level of functional components. This rule is
important because hooks rely on the order in which they are called to maintain
state and effect consistency across renders. Calling hooks conditionally or
within nested functions can lead to unpredictable behavior and bugs.
Example violating the rule:
function MyComponent({ condition }) { if (condition) { const
[value, setValue] = useState(0); // Incorrect: Inside a condition } // ... }
- Explain
the purpose and usage of the useCallback hook in React. Provide examples
of common use cases.
The useCallback hook is used to memoize callback
functions, preventing them from being recreated on each render. This can
improve performance by ensuring that callback dependencies do not change unless
specified in the dependency array.
Example with a memoized callback:
const handleClick = useCallback(() => { // Handle click
event }, []); // Empty dependency array means no dependencies
- What
is the significance of the key prop in React lists, and why should it be
unique among siblings? How can you handle situations where keys might not
be unique?
The key prop in React lists is used to help React
identify and track elements during updates efficiently. Keys should be unique among
siblings to ensure React can correctly reconcile and update components. In
cases where you can't guarantee unique keys, you can use a combination of
unique identifiers or library-generated keys, as previously mentioned.
- Discuss
the concept of Redux Thunk middleware and how it is used for handling
asynchronous actions in Redux. Provide an example.
Redux Thunk is a middleware that allows you to dispatch
functions (thunks) instead of plain actions. It's commonly used for handling
asynchronous actions, such as making API calls, in Redux.
Example of a Redux Thunk action creator:
const fetchUserData = (userId) => { return async
(dispatch) => { try { const response = await fetch(`/api/users/${userId}`); const
data = await response.json(); dispatch({ type: 'FETCH_USER_SUCCESS', payload:
data }); } catch (error) { dispatch({ type: 'FETCH_USER_FAILURE', payload:
error.message }); } }; };
- What
is the purpose of the React.memo higher-order component, and how is it
used to optimize rendering? Provide an example.
React.memo is a higher-order component used to
memoize a functional component, preventing re-renders unless its props change.
It helps optimize rendering by ensuring that a component doesn't update when
its props remain the same.
Example:
const MemoizedComponent = React.memo(function MyComponent(props)
{ // Component rendering logic });
- Explain
the concept of the React Fiber reconciler and how it contributes to
improved performance in React applications.
React Fiber is an internal rewrite of React's core
algorithm. It introduces the concept of a fiber, which allows React to work on
chunks of work and prioritize rendering updates. This enables asynchronous
rendering and concurrent updates, making React more responsive and capable of
handling complex user interfaces without blocking the main thread, thereby
improving performance.
- Discuss
the concept of Higher-Order Components (HOCs) and how they can be used for
code reuse in React applications. Provide an example.
Higher-Order Components (HOCs) are functions that take a
component and return a new component with additional props or behavior. They
are used for code reuse and enhancing component functionality without changing
the component's structure.
Example of a simple HOC:
function withLogger(Component) { return function WithLogger(props)
{ console.log(`Rendered: ${Component.name}`); return <Component {...props}
/>; }; }
- Explain
the concept of React's Context API and how it helps in managing global
state. Provide examples of when and why you might use it.
The React Context API allows you to share data and state
across the component tree without prop drilling. It is useful for managing
global state, such as user authentication, themes, or localization, and
simplifies the passing of data between deeply nested components.
Example of managing theme with Context API (previously
covered):
const ThemeContext = React.createContext('light'); function App()
{ return ( <ThemeContext.Provider value="dark"> <ThemedComponent
/> </ThemeContext.Provider> ); }
- What
is the purpose of React Portals, and provide examples of when and how you
might use them?
React Portals allow you to render components outside their
parent DOM hierarchy. This is useful for scenarios like modals, tooltips, and
overlays where you want to render content in a different part of the DOM.
Example of rendering a modal outside the root (previously
covered):
function Modal({ children }) { return ReactDOM.createPortal(children,
document.getElementById('modal-root')); } function App() { return ( <> <h1>Main
App Content</h1> <Modal> <p>Modal Content</p> </Modal>
</> ); }
- What
is the significance of the dangerouslySetInnerHTML prop in React, and why
should you use it with caution? Provide an example.
dangerouslySetInnerHTML is a prop in React that
allows you to set HTML content inside a component. It should be used with
caution because it can potentially expose your application to cross-site
scripting (XSS) attacks if the HTML content is not trusted.
Example:
function RenderHTML() { const htmlContent = '<div><p>This
is HTML content.</p></div>'; return <div dangerouslySetInnerHTML={{
__html: htmlContent }} />; }
- What
is the purpose of React Portals, and provide examples of when and how you
might use them?
React Portals allow you to render components outside their
parent DOM hierarchy. This is useful for scenarios like modals, tooltips, and
overlays where you want to render content in a different part of the DOM.
Example of rendering a modal outside the root (previously
covered):
function Modal({ children }) { return ReactDOM.createPortal(children,
document.getElementById('modal-root')); } function App() { return ( <> <h1>Main
App Content</h1> <Modal> <p>Modal Content</p> </Modal>
</> ); }
- What
is the significance of the dangerouslySetInnerHTML prop in React, and why
should you use it with caution? Provide an example.
dangerouslySetInnerHTML is a prop in React that
allows you to set HTML content inside a component. It should be used with
caution because it can potentially expose your application to cross-site
scripting (XSS) attacks if the HTML content is not trusted.
Example:
function RenderHTML() { const htmlContent = '<div><p>This
is HTML content.</p></div>'; return <div dangerouslySetInnerHTML={{
__html: htmlContent }} />; }
- Explain
the purpose and usage of the React.StrictMode component in React
applications. Why is it beneficial to wrap your app in StrictMode during
development?
React.StrictMode is a development mode that helps you
identify and address potential problems in your application. It performs
additional checks and warnings during rendering, highlighting issues like
unsafe lifecycle methods and unexpected side-effects. It's particularly helpful
for catching and fixing problems early in development.
To enable Strict Mode, wrap your root component in <React.StrictMode>
in your app's entry point.
- What
are the key differences between React function components and class
components? Provide examples of when you might choose one over the other.
React function components are simpler and more concise
compared to class components. Function components use the useState and useEffect
hooks for managing state and side effects, while class components use this.state
and lifecycle methods.
Example of a function component:
function FunctionComponent() { const [count, setCount] = useState(0);
useEffect(() => { document.title = `Count: ${count}`; }, [count]); return ( <div>
<p>Count: {count}</p> <button onClick={() => setCount(count +
1)}>Increment</button> </div> ); }
Example of a class component (for comparison):
class ClassComponent extends React.Component { constructor(props)
{ super(props); this.state = { count: 0 }; } componentDidMount() { document.title
= `Count: ${this.state.count}`; } componentDidUpdate() { document.title = `Count:
${this.state.count}`; } render() { return ( <div> <p>Count:
{this.state.count}</p> <button onClick={() => this.setState({
count: this.state.count + 1 })}> Increment </button> </div> ); }
}
- Explain
the purpose and usage of the useLayoutEffect hook in React, and provide an
example of a use case for useLayoutEffect.
useLayoutEffect is similar to useEffect but
fires synchronously after all DOM mutations. It's useful when you need to
perform DOM measurements or synchronous actions that may affect layout
immediately after rendering.
Example of using useLayoutEffect for measuring an
element's size:
import { useState, useLayoutEffect, useRef } from 'react'; function
MeasureElementSize() { const [size, setSize] = useState({ width: 0, height: 0
}); const elementRef = useRef(null); useLayoutEffect(() => { const element =
elementRef.current; if (element) { const rect = element.getBoundingClientRect();
setSize({ width: rect.width, height: rect.height }); } }, []); return ( <div
ref={elementRef}> Element size: {size.width} x {size.height} </div> );
}
- Explain
the concept of controlled and uncontrolled components in React forms, and
provide a use case for each.
Controlled components are those where the form element's
value is controlled by React state. Uncontrolled components are those where the
form element manages its own state. Use controlled components when you need to
have full control over form input values and perform validation. Uncontrolled
components may be suitable when integrating with non-React libraries or when
you want to minimize React state management.
Controlled component example (already covered):
function ControlledInput() { const [value, setValue] = useState('');
const handleChange = (e) => { setValue(e.target.value); }; return <input type="text"
value={value} onChange={handleChange} />; }
Uncontrolled component example (already covered):
function UncontrolledInput() { const inputRef = useRef(); const
handleButtonClick = () => { alert(`Input value: ${inputRef.current.value}`);
}; return ( <div> <input type="text" ref={inputRef} /> <button
onClick={handleButtonClick}>Get Value</button> </div> ); }
- Explain
the concept of React error boundaries and how they help in handling errors
gracefully. Provide an example.
React error boundaries are components that catch JavaScript
errors during rendering, allowing you to handle them gracefully and display
fallback UI instead of a crashing application. They help isolate errors and
prevent them from affecting the entire component tree.
Example:
class ErrorBoundary extends React.Component { constructor(props)
{ super(props); this.state = { hasError: false }; } componentDidCatch(error,
errorInfo) { this.setState({ hasError: true }); // Log or report the error } render()
{ if (this.state.hasError) { return <div>Something went wrong.</div>;
} return this.props.children; } } <ErrorBoundary> <MyComponent />
</ErrorBoundary>
- What
is Hoisting and give a real-time example:
Hoisting is a JavaScript behavior where variable and
function declarations are moved to the top of their containing scope during
compilation. This means you can use a variable or function before it's declared
in your code. However, only the declarations are hoisted, not the
initializations.
Example:
console.log(x); // Outputs: undefined var x = 10;
In this example, the var x declaration is hoisted to
the top, but the initialization (x = 10) remains in place. So, x
is undefined when console.log is called.
- What
is a Callback function:
A callback function is a function that is passed as an
argument to another function and is executed after a specific task or event has
occurred. Callbacks are commonly used for handling asynchronous operations,
such as API calls or event handling, where the execution order is not
guaranteed.
Example:
function fetchData(url, callback) { // Simulate an API call setTimeout(()
=> { const data = { message: 'Data fetched successfully' }; callback(data);
}, 1000); } function displayData(data) { console.log(data.message); } fetchData('https://api.example.com/data',
displayData);
In this example, displayData is a callback function
passed to fetchData, which is called when the data is fetched.
- Difference
between map and forEach:
Both map and forEach are array methods in
JavaScript, but they have some differences:
- map
returns a new array with the results of applying a provided function to
each element of the array, creating a new array. It does not modify the
original array.
- forEach
executes a provided function once for each array element, but it does not
create a new array. It is used for side effects (like printing values)
and does not return anything.
Example using map:
const numbers = [1, 2, 3]; const doubled = numbers.map((num)
=> num * 2); console.log(doubled); // Outputs: [2, 4, 6]
Example using forEach:
const numbers = [1, 2, 3]; numbers.forEach((num) => console.log(num
* 2)); // Outputs: 2, 4, 6
- Write
code to Reverse a String without using Methods:
You can reverse a string by iterating over its characters
and building a new string in reverse order.
Example:
function reverseString(input) { let reversed = ''; for (let
i = input.length - 1; i >= 0; i--) { reversed += input[i]; } return
reversed; } const originalString = 'Hello, World!'; const reversedString = reverseString(originalString);
console.log(reversedString); // Outputs: '!dlroW ,olleH'
- What
is Function Currying:
Function currying is a technique in functional programming
where a function that takes multiple arguments is transformed into a series of
functions, each taking a single argument. This allows you to partially apply
arguments and create more specialized functions.
Example:
function add(x) { return function (y) { return x + y; }; } const
add5 = add(5); // Partial application console.log(add5(3)); // Outputs: 8
In this example, add is curried, and you can create
specialized functions like add5 by providing a single argument.
- How
to call API calls parallelly:
To call API calls in parallel, you can use Promise.all
to await multiple promises simultaneously.
Example using Promise.all and fetch:
const urls = ['https://api.example.com/data1', 'https://api.example.com/data2'];
const requests = urls.map((url) => fetch(url)); Promise.all(requests) .then((responses)
=> Promise.all(responses.map((response) => response.json()))) .then((data)
=> { console.log(data); // Array of API responses }) .catch((error) => { console.error('Error:',
error); });
- How
to Call the biggest API call:
To call the largest API call, you can use the appropriate
HTTP request method (e.g., GET, POST) and the API endpoint URL with any required
headers or parameters. You should use a library like axios or fetch
to make the HTTP request in your React application.
Example using axios:
import axios from 'axios'; axios.get('https://api.example.com/largest-api-endpoint')
.then((response) => { console.log('API Response:', response.data); }) .catch((error)
=> { console.error('Error:', error); });
- Toggle
Background Color in React:
You can create a toggle button in React that changes the
background color based on its state.
import React, { useState } from 'react'; function App() { const
[isBlack, setIsBlack] = useState(true); const toggleBackgroundColor = () =>
{ setIsBlack(!isBlack); }; const backgroundColor = isBlack ? 'black' : 'white';
return ( <div style={{ backgroundColor }}> <button onClick={toggleBackgroundColor}>Toggle
Background</button> </div> ); } export default App;
- How
to use DOM elements directly in React:
In React, it's recommended to use refs to interact with DOM
elements directly. You can create a ref using the useRef hook or the React.createRef
method in class components.
Example using useRef:
import React, { useRef, useEffect } from 'react'; function App()
{ const myRef = useRef(null); useEffect(() => { myRef.current.textContent = 'Updated
text'; }, []); return <div ref={myRef}>Initial text</div>; } export
default App;
- Explain
closure and give an example:
A closure is a function that has access to its own scope,
the outer function's scope, and the global scope. It "closes over"
the variables it needs, even after the outer function has finished executing.
Example:
function outer() { const outerVar = 'I am from outer
function'; function inner() { console.log(outerVar); // Accessing outerVar from
the outer scope } return inner; } const closureFunc = outer(); closureFunc(); //
Outputs: "I am from outer function"
- Difference
between useMemo and callback function:
- useMemo
is a hook used for memoization. It caches the result of a function and
returns it when the dependencies specified in the dependency array have
not changed. It's used for optimizing expensive calculations.
- Callback
functions are regular functions that are passed as arguments to other
functions and are invoked later. They are not specifically for
memoization but can be used to achieve various tasks, including handling
asynchronous operations or event handling.
Example of useMemo:
const memoizedValue = useMemo(() => computeExpensiveValue(a,
b), [a, b]);
Example of a callback function:
function fetchData(url, callback) { // Fetch data from the
URL and invoke the callback when done }
- Difference
between useMemo and callback function:
- useMemo
is a hook used for memoization. It caches the result of a function and
returns it when the dependencies specified in the dependency array have
not changed. It's used for optimizing expensive calculations.
- Callback
functions are regular functions that are passed as arguments to other
functions and are invoked later. They are not specifically for
memoization but can be used to achieve various tasks, including handling
asynchronous operations or event handling.
Example of useMemo:
const memoizedValue = useMemo(() =>
computeExpensiveValue(a, b), [a, b]);
Example of a callback function:
function fetchData(url, callback) { // Fetch data from the
URL and invoke the callback when done }
- Explain
React Architecture:
React follows a component-based architecture. At the core,
React is composed of the following elements:
- Components:
These are the building blocks of a React application. Components are
reusable and can be either functional or class-based.
- Virtual
DOM: React maintains a lightweight representation of the actual DOM
in memory called the Virtual DOM. This allows React to efficiently update
the real DOM by minimizing the number of actual DOM manipulations.
- Props:
Components can receive data through props (short for properties). Props
are read-only and help pass data from parent components to child
components.
- State:
Components can have their own state, which is mutable and used to manage
internal data. State changes trigger re-renders.
- Reconciliation:
React's diffing algorithm compares the Virtual DOM with the real DOM to
determine the minimum number of updates needed to keep the UI in sync.
- Component
Lifecycle: Components have lifecycle methods like componentDidMount,
componentDidUpdate, and componentWillUnmount, which allow
developers to perform actions at specific points in a component's life.
- Explain
the Life Cycle methods of React JS:
In class-based components, React provides several lifecycle
methods:
- componentDidMount:
Called after the component is inserted into the DOM. It's commonly used
for data fetching and initialization.
- componentDidUpdate:
Invoked when the component updates (e.g., state changes or prop updates).
Useful for managing side effects or updating the DOM in response to
changes.
- componentWillUnmount:
Called just before a component is removed from the DOM. It's used for
cleaning up resources or event handlers.
- shouldComponentUpdate:
Allows optimization by preventing unnecessary re-renders.
- componentDidCatch:
Handles errors in child components when they're not caught in regular
try-catch blocks.
In functional components, lifecycle methods are replaced by
React Hooks like useEffect for side effects and useLayoutEffect
for synchronous layout updates.
- Explain
the basic setup and advanced configurations for a React application:
- Basic
Setup:
- Install
Node.js and npm if not already installed.
- Create
a React app using npx create-react-app app-name.
- Navigate
to the app directory with cd app-name.
- Start
the development server with npm start.
- Advanced
Configurations:
- Custom
Webpack/Babel configurations: For advanced optimizations.
- Code
splitting: Use React.lazy and Suspense for dynamic imports.
- Environment
variables: Use .env files to manage environment-specific
configurations.
- State
management: Implement state management with Redux or Mobx for complex
apps.
- Routing:
Integrate a routing library like React Router.
- Server-side
rendering: Implement server-side rendering with frameworks like Next.js.
- Build
and deployment: Set up deployment pipelines for CI/CD using tools like
Netlify, Vercel, or AWS.
- Explain
the key concepts of Redux and how middleware can be used in Redux:
- Redux
Key Concepts:
- Store:
A single source of truth for the application's state.
- Actions:
Plain JavaScript objects that describe changes to the state.
- Reducers:
Functions that specify how the state changes in response to actions.
- Middleware:
Functions that extend Redux's capabilities, commonly used for async
operations, logging, or routing.
- Connect:
A higher-order component or hook used to connect components to the Redux
store.
- Middleware
in Redux: Middleware in Redux is a powerful concept that allows you
to intercept and process actions before they reach the reducers. It's
commonly used for asynchronous actions. Middleware can be added using the
applyMiddleware function. Some popular middleware includes:
- redux-thunk:
Enables asynchronous actions by allowing action creators to return
functions.
- redux-saga:
Provides a more structured way to manage side effects with generators.
- redux-logger:
Logs actions and state changes for debugging.
- Custom
middleware: You can write custom middleware to handle specific tasks,
like authentication.
- Explain
ES6 features:
ES6 (ECMAScript 2015) introduced several important features
to JavaScript:
- Arrow
Functions: A concise way to write functions with implicit return.
- Template
Literals: Use backticks to create strings with embedded expressions.
- Destructuring:
Easily extract values from objects and arrays.
- let
and const: Block-scoped variable declarations, replacing var.
- Classes:
A more structured way to create constructor functions for objects.
- Modules:
Improved module system for organizing and importing/exporting code.
- Promises:
A standard way to work with asynchronous operations, providing better
error handling.
- async/await:
Simplifies asynchronous code, allowing asynchronous functions to look
synchronous.
- Rest
and Spread Operators: ... for packing and unpacking values in
objects and arrays.
- Default
Function Parameters: Set default values for function parameters.
- Map
and Set: New data structures for storing data with unique keys.
- Symbols:
Unique and immutable values that can be used as object properties.
- Generators:
Functions that can be paused and resumed.
These ES6 features have significantly improved the
JavaScript language and have become essential in modern web development.
- How to make API calls in a React
application:
To make API calls in a React application, you can use
JavaScript fetch, Axios, or other HTTP client libraries. You typically make API
calls within a component's lifecycle methods or using React Hooks like useEffect.
Example using fetch and useEffect:
Code Snippet
import React, { useState, useEffect } from 'react'; function
App() { const [data, setData] = useState([]); useEffect(() => { fetch('https://api.example.com/data')
.then((response) => response.json()) .then((result) => setData(result)) .catch((error)
=> console.error('API Error:', error)); }, []); return ( <div>
{data.map((item) => ( <div key={item.id}>{item.name}</div> ))} </div>
); }
- How
to interact or communicate with a Node.js server in a React application:
To interact with a Node.js server in a React application,
you can use HTTP requests (e.g., GET, POST) to communicate with APIs provided
by the Node.js server. This communication can be achieved using the fetch
API, Axios, or any other HTTP client library.
Example using Axios:
Code Snippet
import axios from 'axios'; // Making a GET request to a
Node.js server endpoint axios.get('https://node-server-api.com/data') .then((response)
=> { // Handle the server response }) .catch((error) => { // Handle
errors });
You can also use WebSocket for real-time communication
between React and a Node.js server.
- How
does Virtual DOM work in React:
The Virtual DOM is a key concept in React. Here's how it
works:
- Whenever
there's a change in a React component's state, the component re-renders.
- Instead
of directly updating the real DOM, React updates a virtual representation
of the DOM called the Virtual DOM.
- React
then compares the current Virtual DOM with the previous one to identify
the differences or "diffs" (what needs to change).
- React
generates a minimal set of changes needed to update the real DOM.
- These
changes are applied to the real DOM, ensuring that only the necessary
updates are made.
This process is more efficient than direct manipulation of
the real DOM, resulting in better performance and faster updates.
- What
is JSX:
JSX stands for "JavaScript XML" and is an
extension to JavaScript used in React. It allows developers to write HTML-like
code within JavaScript, making it easier to create and structure React
components. JSX is then transpiled to JavaScript by tools like Babel before
it's executed in the browser.
Example of JSX:
Code Snippet
const element = <h1>Hello, React!</h1>;
In this code, the JSX <h1>Hello, React!</h1>
is transpiled into React.createElement('h1', null, 'Hello, React!')
under the hood.
- Explain
the types of components in React:
In React, there are two main types of components:
- Functional
Components: These are stateless components that are primarily used for
presenting UI. With the introduction of React Hooks, they can also handle
state and side effects, making them the most common type of component in
modern React applications.
Example:
Code Snippet
function FunctionalComponent(props) { // Component logic }
- Class
Components: These are ES6 classes that extend React.Component.
Class components are traditionally used for stateful components with
lifecycle methods. However, with the introduction of React Hooks, their
use has decreased.
Example:
Code Snippet
class ClassComponent extends React.Component { // Component
logic }
Both functional and class components can be used in React,
but functional components are preferred for their simplicity and readability.
Class components are still relevant in legacy codebases or when using certain
features like the old-style lifecycle methods.
- Difference
between state and props:
- State:
State is used to manage and store data that can be changed over time. It
belongs to the component in which it is defined and is mutable. State is
typically managed in class components or using the useState Hook
in functional components.
- Props
(Properties): Props are read-only and are used to pass data from a
parent component to a child component. They are used for communication
between components and help make components reusable and maintainable.
- What
is a Controlled Component in React:
A controlled component is a React component that derives its
state from React's state. It means that the component's value is controlled by
React, and you need to update the component's state to change its value.
Controlled components are often used in forms, where you bind the component's
value to state and handle changes through event handlers.
Example of a controlled input component:
Code Snippet
import React, { Component } from 'react'; class ControlledInput
extends Component { constructor() { super(); this.state = { value: '' }; }
handleChange = (event) => { this.setState({ value: event.target.value }); } render()
{ return ( <input type="text" value={this.state.value} onChange={this.handleChange}
/> ); } }
- What
is a higher-order component (HOC)? Explain with an example:
A higher-order component (HOC) is a function that takes a
component and returns a new component with enhanced functionality. HOCs are
used for code reuse, logic abstraction, and prop manipulation.
Example of a simple HOC that adds a user prop to a
component:
Code Snippet
import React, { Component } from 'react'; const withUser = (WrappedComponent)
=> { return class extends Component { render() { return <WrappedComponent
user="John" {...this.props} />; } }; }; // Usage class UserProfile
extends Component { render() { return <div>User Profile:
{this.props.user}</div>; } } const UserProfileWithUser = withUser(UserProfile);
- Explain
Redux:
Redux is a predictable state container for JavaScript
applications, primarily used with React. It provides a global state management
system for managing application data in a predictable and consistent way. Key
concepts in Redux include:
- Store:
A single source of truth for the application's state.
- Actions:
Plain JavaScript objects that describe changes to the state.
- Reducers:
Functions that specify how the state changes in response to actions.
- Middleware:
Functions that extend Redux's capabilities (e.g., for handling async
actions).
- Connect:
A higher-order component or hook used to connect components to the Redux
store.
Redux is often used when state management becomes complex or
when multiple components need access to the same state.
- Explain
the new features introduced in HTML5:
HTML5 introduced several new features and elements,
including:
- Canvas:
An HTML element for drawing graphics, allowing you to create interactive
visual content.
- Video
and Audio: <video> and <audio> elements for
embedding multimedia content without plugins.
- Semantic
Elements: Elements like <header>, <nav>,
and <section> for structuring web content in a more
meaningful way.
- Form
Enhancements: New input types (e.g., date, email, number)
and the <datalist> element for better form control.
- Web
Storage: localStorage and sessionStorage for storing
data on the client side.
- Geolocation:
The Geolocation API for accessing a user's location.
- Drag
and Drop: Native support for drag-and-drop interactions.
- Web
Workers: A way to run JavaScript code in the background, allowing for
multi-threading.
- Offline
Web Applications: HTML5 introduced Application Cache and Service
Workers for creating offline-capable web apps.
These features improved the capabilities and performance of
web applications and made it easier to develop interactive and responsive
websites.
Comments
Post a Comment