React Fundamentals
-
What is React? π€
- Explanation: React is an open-source JavaScript library for building user interfaces, particularly for single-page applications. It allows developers to create reusable UI components.
- Use Case: Used to develop dynamic web applications where data changes frequently, such as dashboards.
-
What are the main features of React? π
-
Explanation:
- Component-Based Architecture: Reusable UI components.
- JSX: A syntax extension that allows mixing HTML with JavaScript.
- Virtual DOM: Efficient updates to the UI by minimizing direct DOM manipulations.
- One-Way Data Binding: Ensures data flows in one direction for easier debugging.
- Use Case: Building scalable applications with a clear structure.
-
Explanation:
-
What is JSX? π
- Explanation: JSX (JavaScript XML) is a syntax extension for JavaScript that allows writing HTML elements in JavaScript. It simplifies the creation of React components.
- Example:
const element = <h1>Hello, World!</h1>;
- Use Case: Makes the code more readable and easier to write when creating UI components.
-
Explain the concept of components in React. π§©
- Explanation: Components are independent, reusable pieces of UI. They can be functional or class-based and can accept inputs (props).
- Example:
function Greeting(props) { return <h1>Hello, {props.name}!</h1>; }
- Use Case: Breaking down complex UIs into smaller, manageable parts.
-
What is the difference between a class component and a functional component? βοΈ
-
Explanation:
-
Class Components: Extend from
React.Component
, can have lifecycle methods, and manage state. - Functional Components: Simpler, used for stateless components, but with hooks, they can manage state and lifecycle.
-
Class Components: Extend from
- Example:
// Class Component class MyComponent extends React.Component { render() { return <div>Hello, Class!</div>; } } // Functional Component function MyComponent() { return <div>Hello, Functional!</div>; }
-
Explanation:
- Use Case: Use functional components for simpler, stateless parts of the UI, class components for more complex behavior.
-
What are props in React? π¦
- Explanation: Props (short for properties) are read-only attributes passed from a parent component to a child component. They allow data to flow within the component hierarchy.
- Example:
function Greeting(props) { return <h1>Hello, {props.name}!</h1>; }
- Use Case: Passing data to components to create dynamic UIs.
-
How do you manage state in React? ποΈ
-
Explanation: State can be managed using the
useState
hook in functional components or throughthis.state
in class components. It allows components to keep track of data that changes over time. - Example:
// Functional Component const [count, setCount] = useState(0);
-
Explanation: State can be managed using the
- Use Case: Managing form inputs, toggles, and any UI element that changes based on user interaction.
-
What is the difference between State and Props in React? π
-
Explanation:
- State: Managed within the component, mutable, and determines the componentβs behavior and rendering.
- Props: Passed to components, immutable, and used to communicate between components.
- Use Case: Use state for internal data management, props for passing data and behavior to child components.
-
Explanation:
-
What is the Virtual DOM in React? π₯οΈ
- Explanation: The Virtual DOM is a lightweight copy of the actual DOM. React updates this virtual representation first, compares it with the real DOM, and only updates the changed parts for performance optimization.
- Use Case: Enhancing performance in applications where frequent updates occur, reducing the number of direct DOM manipulations.
Lifecycle & Hooks
-
What are lifecycle methods in React? β³
- Explanation: Lifecycle methods are hooks in class components that allow you to run code at specific points in a componentβs life cycle (mounting, updating, and unmounting).
-
Example:
componentDidMount()
componentDidUpdate()
componentWillUnmount()
- Use Case: Performing side effects such as API calls after a component mounts.
-
What is the difference between ComponentDidMount, ComponentDidUpdate, and ComponentWillUnmount in class components? π°οΈ
-
Explanation:
- componentDidMount: Invoked immediately after a component is mounted. Ideal for fetching data.
- componentDidUpdate: Invoked immediately after updating occurs. Suitable for operations based on prop changes.
- componentWillUnmount: Invoked immediately before a component is unmounted. Useful for cleanup (e.g., canceling API requests).
- Use Case: Managing resources effectively and preventing memory leaks.
-
Explanation:
-
What is the useEffect Hook and how is it different from useLayoutEffect? β²οΈ
-
Explanation:
- useEffect: A hook that runs side effects after rendering, ideal for data fetching, subscriptions, or manually changing the DOM.
- useLayoutEffect: Similar, but it runs synchronously after all DOM mutations. Useful for measuring the layout.
- Example:
useEffect(() => { // side effect code }, [dependencies]);
-
Explanation:
- **Use Case:** Managing side effects in functional components without blocking the browser's painting.
-
What is the useState Hook and how do you use it? ποΈ
-
Explanation:
useState
is a hook that lets you add state to functional components. It returns a state variable and a function to update it. - Example:
const [count, setCount] = useState(0);
-
Explanation:
- **Use Case:** Managing local component state like user input or toggles.
-
What is the useCallback Hook and when would you use it? π
-
Explanation:
useCallback
returns a memoized callback function that only changes if one of the dependencies has changed. It helps prevent unnecessary re-renders. - Example:
const memoizedCallback = useCallback(() => { doSomething(a, b); }, [a, b]);
-
Explanation:
- **Use Case:** Passing callbacks to optimized child components that rely on reference equality to prevent re-renders.
-
What is the difference between useMemo and useCallback? π§ vs π
-
Explanation:
- useMemo: Memoizes the result of a computation.
- useCallback: Memoizes the function itself.
- Example:
const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);
-
Explanation:
- **Use Case:** Use `useMemo` for expensive calculations, and `useCallback` for functions passed as props.
-
What is useReducer Hook and when should you use it? π
-
Explanation:
useReducer
is a hook for managing more complex state logic in a functional component, often used when the state depends on previous states. - Example:
const [state, dispatch] = useReducer(reducer, initialState);
-
Explanation:
- **Use Case:** Handling state in larger components where multiple state variables are related.
-
What is the useRef Hook and how is it used? π
-
Explanation:
useRef
returns a mutable ref object whose.current
property is initialized to the passed argument. It can hold a reference to a DOM element or a mutable value. - Example:
const inputRef = useRef(null); const focusInput = () => { inputRef.current.focus(); };
-
Explanation:
- **Use Case:** Accessing DOM elements directly for input focus, animations, or integrating with third-party libraries.
-
What is the purpose of the useContext Hook? π
-
Explanation:
useContext
allows you to consume context directly in functional components without needing to wrap them in a Context.Consumer. - Example:
const value = useContext(MyContext);
-
Explanation:
- **Use Case:** Simplifying the consumption of context for global state management.
-
How do you create a custom hook? π§
- Explanation: A custom hook is a JavaScript function that starts with "use" and can call other hooks. It can encapsulate logic that needs to be reused across components.
- Example:
function useFetch(url) { const [data, setData] = useState(null); useEffect(() => { fetch(url).then(response => response.json()).then(setData); }, [url]); return data; }
- **
Use Case:** Reusing stateful logic, like fetching data or form handling.
-
What is React.memo and how is it different from useMemo? π
-
Explanation:
React.memo
is a higher-order component that memoizes a component, preventing unnecessary re-renders.useMemo
is used to memoize values within a component. - Example:
const MemoizedComponent = React.memo(MyComponent);
-
Explanation:
- **Use Case:** Optimizing functional components that render the same output given the same props.
State Management & Context
-
How does React handle state management? What are some libraries for managing state in larger applications? π¦
-
Explanation: React provides built-in state management through
useState
anduseReducer
. For larger applications, libraries like Redux, MobX, and Recoil can be used to manage global state. - Use Case: Using Redux for a complex application to manage the global state across multiple components.
-
Explanation: React provides built-in state management through
-
What is the Context API in React and how do you create a Context? π
-
Explanation: The Context API allows you to share values (like state) between components without prop drilling. It is created using
React.createContext()
. - Example:
const MyContext = React.createContext();
-
Explanation: The Context API allows you to share values (like state) between components without prop drilling. It is created using
- **Use Case:** Sharing theme settings or user authentication status across components.
-
What is Prop Drilling and how can it be avoided? π
- Explanation: Prop drilling is the process of passing data through many layers of components. It can be avoided using the Context API or state management libraries.
- Use Case: Using Context API to eliminate the need to pass props through every component.
-
What are Higher-Order Components (HOCs)? ποΈ
- Explanation: HOCs are functions that take a component and return a new component. They are used to share common functionality across multiple components.
- Example:
const withExtraInfo = (WrappedComponent) => { return (props) => { return <WrappedComponent {...props} extraInfo="Extra Data" />; }; };
- **Use Case:** Adding logging, data fetching, or theming to components without modifying their structure.
-
What are Controlled and Uncontrolled Components in React? ποΈ
-
Explanation:
- Controlled Components: The componentβs state is controlled by React. The input value is managed through the component state.
- Uncontrolled Components: The input maintains its own internal state. React does not control the input value.
- Example:
// Controlled <input type="text" value={value} onChange={e => setValue(e.target.value)} /> // Uncontrolled <input type="text" ref={inputRef} />
-
Explanation:
- **Use Case:** Controlled components for forms, uncontrolled for simple input scenarios.
-
What is a ForwardRef in React? π
-
Explanation:
ForwardRef
is a React API that allows a parent component to pass a ref through a component to one of its children. - Example:
const FancyInput = React.forwardRef((props, ref) => ( <input ref={ref} className="fancy-input" /> ));
-
Explanation:
- **Use Case:** Allowing parent components to access the ref of child components for DOM manipulations.
Performance Optimization
-
How do you optimize performance in a React app? π
-
Explanation:
- Use memoization (
React.memo
,useMemo
,useCallback
). - Code splitting and lazy loading with
React.lazy
. - Optimize rendering using the Virtual DOM.
- Avoid inline functions and anonymous functions in render.
- Use memoization (
- Use Case: Ensuring a smooth user experience in applications with frequent updates or large datasets.
-
Explanation:
-
What is React.lazy and how do you use it? π΄
-
Explanation:
React.lazy
allows you to dynamically import components as they are needed, enabling code splitting. - Example:
const OtherComponent = React.lazy(() => import('./OtherComponent'));
-
Explanation:
- **Use Case:** Reducing the initial load time by loading components only when they are required.
-
What is Code Splitting in React? π¦
- Explanation: Code splitting is the practice of breaking your code into smaller chunks which can be loaded on demand. This improves loading times and reduces the initial bundle size.
- Use Case: Loading routes only when the user navigates to them.
-
What are some performance optimization techniques in SSR? π₯οΈ
-
Explanation:
- Minimize server-side rendering time by optimizing data fetching.
- Use caching strategies to store server-rendered pages.
- Implement code splitting on the server.
- Use Case: Improving the speed and efficiency of server-rendered applications.
-
Explanation:
-
How do you handle large lists in React? π
-
Explanation: Use techniques like windowing or virtualization with libraries such as
react-window
orreact-virtualized
to only render what is visible on the screen. - Use Case: Efficiently rendering long lists (e.g., thousands of items) without performance issues.
-
Explanation: Use techniques like windowing or virtualization with libraries such as
Advanced Concepts
-
What is Server-Side Rendering (SSR) in React? π
- Explanation: SSR is the process of rendering web pages on the server instead of in the browser. It improves performance and SEO by delivering fully rendered pages.
- Use Case: Websites that require fast loading and SEO optimization.
-
What is Client-Side Rendering (CSR) in React? π»
- Explanation: CSR means that the web page is rendered in the browser, allowing for a dynamic, interactive user experience. The initial load might be slower compared to SSR.
- Use Case: Single-page applications where user interaction is crucial.
-
How is SSR implemented in React using Next.js? βοΈ
-
Explanation: Next.js simplifies the process of SSR in React by providing built-in functions for data fetching (
getServerSideProps
) that run on the server. - Example:
export async function getServerSideProps() { const res = await fetch('https://api.example.com/data'); const data = await res.json(); return { props: { data } }; }
-
Explanation: Next.js simplifies the process of SSR in React by providing built-in functions for data fetching (
- **Use Case:** Building SEO-friendly React applications with fast loading times.
-
What is the Hydration Process in SSR? π§
- Explanation: Hydration is the process of attaching event listeners to the server-rendered HTML when it is loaded in the browser, turning it into a fully interactive React application.
- Use Case: Ensuring the React app is interactive without requiring a complete re-render.
-
What is Static Site Generation (SSG), and how does it differ from SSR and CSR? ποΈ
- Explanation: SSG generates HTML at build time, serving static pages. Unlike SSR (runtime rendering) and CSR (client-side rendering), SSG is faster but less dynamic.
- Use Case: Blogs or documentation sites where content does not change often.
-
What is Incremental Static Regeneration (ISR)? π
- Explanation: ISR allows you to update static pages incrementally without needing to rebuild the entire site. You can define a revalidation period to refresh content.
- Use Case: E-commerce sites where products change frequently but static generation is still desirable.
-
How do you combine CSR and SSR in a React app? π
- Explanation: You can leverage frameworks like Next.js to implement both CSR and SSR in your application. Use SSR for initial page loads and CSR for subsequent navigation.
- Use Case: Hybrid applications that need both fast initial loading and interactivity.
-
What is React Hydration Error, and how can you avoid it? π¨
- Explanation: Hydration errors occur when the server-rendered markup does not match the client-side rendered markup. This can lead to UI inconsistencies.
- Solution: Ensure that the server and client render the same output by avoiding state-based rendering in the initial render.
- Use Case: Maintaining consistency between SSR and CSR rendered components.
React Router & Navigation
-
How does React Router work? π€οΈ
- Explanation: React Router is a library that enables dynamic routing in React applications. It uses the browser's history API to keep UI in sync with the URL.
- Use Case: Creating multi-page applications with navigation between different components without full page reloads.
-
How do you set up a basic router in React Router? βοΈ
-
Explanation: Import
BrowserRouter
andRoute
fromreact-router-dom
, then define routes within theBrowserRouter
. - Example:
import { BrowserRouter as Router, Route } from 'react-router-dom'; function App() { return ( <Router> <Route path="/" component={Home} /> <Route path="/about" component={About} /> </Router> ); }
-
Explanation: Import
- **Use Case:** Navigating between components based on the URL path.
- What are nested routes in React Router? π -
Explanation: Nested routes allow you to define child routes within parent routes, enabling complex routing structures.
- Example:
```jsx
<Route path="/dashboard">
<Dashboard>
<Route path="analytics" component={Analytics} />
<Route path="settings" component={Settings} />
</Dashboard>
</Route>
```
- **Use Case:** Organizing routing for a dashboard with multiple sections.
-
What is the purpose of the useHistory Hook in React Router? π
-
Explanation: The
useHistory
hook gives access to the history instance used by React Router, allowing navigation programmatically. - Example:
const history = useHistory(); const handleClick = () => { history.push('/home'); };
-
Explanation: The
- **Use Case:** Redirecting users after form submissions or other actions.
Error Handling & Testing
-
How do you handle errors in React components? π οΈ
- Explanation: Use error boundaries to catch JavaScript errors in the component tree and display a fallback UI. Implement try-catch blocks in async functions.
- Example:
class ErrorBoundary extends React.Component { constructor(props) { super(props); this.state = { hasError: false }; } static getDerivedStateFromError(error) { return { hasError: true }; } componentDidCatch(error, errorInfo) { // Log error to an error reporting service } render() { if (this.state.hasError) { return <h1>Something went wrong.</h1>; } return this.props.children; } }
- **Use Case:** Preventing app crashes by displaying user-friendly error messages.
-
What is Reactβs Strict Mode and why do we use it? π¨
- Explanation: Strict Mode is a development tool that helps to identify potential problems in an application by highlighting unsafe lifecycle methods, legacy API usage, and more.
- Use Case: Improving the quality of code by enforcing best practices during development.
-
How do you test a React component? π
- Explanation: You can test React components using libraries like Jest and React Testing Library. You can write unit tests to check rendering, events, and UI changes.
- Example:
test('renders learn react link', () => { render(<App />); const linkElement = screen.getByText(/learn react/i); expect(linkElement).toBeInTheDocument(); });
- **Use Case:** Ensuring components behave as expected under different scenarios.
-
What is shallow rendering in testing? π¬
- Explanation: Shallow rendering is a testing technique where you render a component without its child components, allowing you to isolate and test the component in isolation.
- Use Case: Testing component logic without worrying about child components.
-
What is the purpose of the React Testing Library? π
- Explanation: React Testing Library focuses on testing components from the user's perspective, encouraging best practices in testing by using real DOM interactions.
- Use Case: Writing tests that closely resemble user interactions to ensure functionality works as expected.
Miscellaneous
-
What are React Fragments and why do we use them? π§©
-
Explanation: React Fragments allow you to group multiple children without adding extra nodes to the DOM. They can be declared with
<Fragment>
or<>
shorthand. - Example:
return ( <Fragment> <ChildA /> <ChildB /> </Fragment> );
-
Explanation: React Fragments allow you to group multiple children without adding extra nodes to the DOM. They can be declared with
- **Use Case:** Returning multiple elements from a component without wrapping them in a div.
-
What are Render Props in React? π
- Explanation: Render Props is a technique for sharing code between React components using a prop whose value is a function.
- Example:
const DataProvider = ({ render }) => { const data = fetchData(); return render(data); }; <DataProvider render={data => <DisplayData data={data} />} />;
- **Use Case:** Sharing data-fetching logic between multiple components.
-
What is the purpose of the key prop in React? π
-
Explanation: The
key
prop is a special string attribute that helps React identify which items have changed, are added, or are removed, optimizing rendering. - Example:
{items.map(item => ( <ListItem key={item.id} item={item} /> ))}
-
Explanation: The
- **Use Case:** Maintaining the state of list items when the list changes.
-
What is the difference between Synthetic Events and normal events in React? β‘
- Explanation: Synthetic events are a cross-browser wrapper around the browser's native events, ensuring consistent behavior across different browsers. They are normalized and pooled by React for performance.
- Use Case: Ensuring consistent event handling in a React application.
-
What is the significance of the className attribute in React? π¨
-
Explanation: The
className
attribute is used in React instead of the standardclass
attribute to apply CSS classes to elements, asclass
is a reserved keyword in JavaScript. - Example:
<div className="my-class">Content</div>
-
Explanation: The
- **Use Case:** Styling React components with CSS.
-
How do you style React components? π¨
- Explanation: You can style React components using CSS stylesheets, inline styles, CSS modules, or libraries like styled-components.
- Example:
const style = { color: 'blue' }; <div style={style}>Styled Text</div>
- **Use Case:** Applying styles to components dynamically.
-
What are CSS Modules and styled-components in React? π
-
Explanation:
- CSS Modules: Allow you to write CSS that is scoped to a single component, avoiding global scope issues.
- Styled-components: A library for styling components using tagged template literals, enabling dynamic styling based on props.
- Use Case: Organizing and managing styles effectively in large applications.
-
Explanation:
-
How do you handle form submission and validation in React? π
- Explanation: Use controlled components to manage form state. Implement validation using libraries like Formik or validate fields on input changes.
- Example:
const handleSubmit = (e) => { e.preventDefault(); // Validation logic }; <form onSubmit={handleSubmit}> <input type="text" value={value} onChange={handleChange} /> <button type="submit">Submit</button> </form>
- **Use Case:** Ensuring user input is correctly handled and validated before submission.
Top comments (0)