From 81983b6b063856932e8bf93aa3e36068b8905977 Mon Sep 17 00:00:00 2001 From: Kamran Ahmed Date: Mon, 18 Sep 2023 16:15:12 +0100 Subject: [PATCH] Add more questions --- .../content/controlled-vs-uncontrolled.md | 15 +- .../react/content/pure-components.md | 27 ++++ .../react/content/re-renders.md | 13 ++ .../react/content/react-performance.md | 28 ---- .../react/content/ref-forwarding.md | 55 ++++++++ .../react/content/set-state.md | 17 +++ .../react/content/synthetic-events.md | 18 +++ src/data/question-groups/react/react.md | 133 ++++++++++++++++-- 8 files changed, 268 insertions(+), 38 deletions(-) create mode 100644 src/data/question-groups/react/content/pure-components.md create mode 100644 src/data/question-groups/react/content/re-renders.md delete mode 100644 src/data/question-groups/react/content/react-performance.md create mode 100644 src/data/question-groups/react/content/ref-forwarding.md create mode 100644 src/data/question-groups/react/content/set-state.md create mode 100644 src/data/question-groups/react/content/synthetic-events.md diff --git a/src/data/question-groups/react/content/controlled-vs-uncontrolled.md b/src/data/question-groups/react/content/controlled-vs-uncontrolled.md index 4b5f856c3..397ab89f1 100644 --- a/src/data/question-groups/react/content/controlled-vs-uncontrolled.md +++ b/src/data/question-groups/react/content/controlled-vs-uncontrolled.md @@ -1,3 +1,14 @@ -JSX stands for JavaScript XML and it is an extension to the JavaScript language syntax. It is used with React to describe what the user interface should look like. By using JSX, we can write HTML structures in the same file that contains JavaScript code. This makes the code easier to understand and debug. +A Controlled Component is one that takes its current value through props and notifies changes through callbacks like `onChange`. A parent component "controls" it by handling the callback and managing its own state and passing the new values as props to the controlled component. You could also call this a "dumb component". -It is basically a syntactic sugar around `React.createElement()` function. \ No newline at end of file +A Uncontrolled Component is one that stores its own state internally, and you query the DOM using a `ref` to find its current value when you need it. This is a bit more like traditional HTML. + +Most native React form components support both controlled and uncontrolled usage: + +```jsx +// Controlled: + + +// Uncontrolled: + +// Use `inputRef.current.value` to read the current value of +``` \ No newline at end of file diff --git a/src/data/question-groups/react/content/pure-components.md b/src/data/question-groups/react/content/pure-components.md new file mode 100644 index 000000000..ea409abae --- /dev/null +++ b/src/data/question-groups/react/content/pure-components.md @@ -0,0 +1,27 @@ +Pure components re-render only when the props passed to the component changes. For example, if you have a pure child component inside a parent component state changes in the parent component will not re-render the child component unless the props passed to the child component change. + +To create a pure component, you can use the `memo` function from React. It is a higher order component which takes a component as an argument and returns a new component. The new component renders only if the props change. + +```jsx +import React, { memo } from 'react'; + +const ChildComponent = ({ name }) => { + console.log('Rendering child component'); + return
{name}
; +}; + +const PureChildComponent = memo(ChildComponent); + +const ParentComponent = () => { + const [count, setCount] = useState(0); + const [name, setName] = useState('John'); + + return ( +
+ + + +
+ ); +}; +``` \ No newline at end of file diff --git a/src/data/question-groups/react/content/re-renders.md b/src/data/question-groups/react/content/re-renders.md new file mode 100644 index 000000000..95874a441 --- /dev/null +++ b/src/data/question-groups/react/content/re-renders.md @@ -0,0 +1,13 @@ +Unnecessary re-renders in components can occur due to several reasons, and it's important to optimize your code to minimize them for better performance. + +Here are some common reasons for unnecessary re-renders in functional components: + +- **Using inline functions in JSX props**: If you pass an inline function as a prop to child components, those components will get re-rendered every time the parent component re-renders. This is because a new function is created on every render. You can optimize this by using `useCallback` hook to memoize the function. +- **Using `useState` hook with objects**: If you use `useState` hook with objects, you need to make sure that you are not mutating the object. If you mutate the object, React will not be able to detect the change and will not re-render the component. You can optimize this by using `useReducer` hook instead of `useState` hook. +- **Using `useEffect` hook without dependencies**: If you use `useEffect` hook without dependencies, it will run on every render. You can optimize this by passing an empty array as the second argument to `useEffect` hook. +- **Parent Component Re-renders**: If a parent component re-renders, all its child components will also re-render. You can optimize this by using `React.memo` to memoize the child component where possible. +- **Global State Changes**: If you use global state management libraries like Redux, MobX, etc., and the global state changes, all the components that use that state will re-render. You can optimize this by using `useSelector` hook to select only the state that you need in a component. +- **Misusing Context**: If you use Context API to pass data to child components, and the data changes, all the child components will re-render. You can optimize this by using `useContext` hook to select only the data that you need in a component. + +You can also use `React.StrictMode` to detect potential problems in your code that could cause unnecessary re-renders. + diff --git a/src/data/question-groups/react/content/react-performance.md b/src/data/question-groups/react/content/react-performance.md deleted file mode 100644 index 69e218f06..000000000 --- a/src/data/question-groups/react/content/react-performance.md +++ /dev/null @@ -1,28 +0,0 @@ -To improve the performance of React app, we can use the following techniques which are not limited to. I would recommend to read [React docs](https://reactjs.org/docs/optimizing-performance.html) for more details. - -- Use production build -- Use suspense with lazy loading -- Avoid unnecessary re-renders -- Memoize expensive computations -- Monitor performance with React Profiler -- ... - -And more. Here's a test code snippet to demonstrate the performance of React app: - -```html - - - - - - - Document - - - -``` - -In the above code snippet, we have a simple HTML page with no CSS and JS. Let's add a React app to it. diff --git a/src/data/question-groups/react/content/ref-forwarding.md b/src/data/question-groups/react/content/ref-forwarding.md new file mode 100644 index 000000000..e0edab34a --- /dev/null +++ b/src/data/question-groups/react/content/ref-forwarding.md @@ -0,0 +1,55 @@ +By default, each component’s DOM nodes are private. However, sometimes it’s useful to expose a DOM node to the parent—for example, to allow focusing it. To opt in, wrap your component definition into `forwardRef()`: + +```jsx +import { forwardRef } from 'react'; + +const MyInput = forwardRef(function MyInput(props, ref) { + const { label, ...otherProps } = props; + return ( + + ); +}); +``` + +You will receive a `ref` as the second argument after props. Pass it to the DOM node that you want to expose: + +```jsx +import { forwardRef } from 'react'; + +const MyInput = forwardRef(function MyInput(props, ref) { + const { label, ...otherProps } = props; + return ( + + ); +}); +``` + +This lets the parent Form component access their `` DOM node exposed by `MyInput`: + +```jsx +function Form() { + const ref = useRef(null); + + function handleClick() { + ref.current.focus(); + } + + return ( +
+ + + + ); +} +``` + +This Form component passes a ref to `MyInput`. The `MyInput` component forwards that ref to the `` browser tag. As a result, the `Form` component can access that `` DOM node and call `focus()` on it. + diff --git a/src/data/question-groups/react/content/set-state.md b/src/data/question-groups/react/content/set-state.md new file mode 100644 index 000000000..87ded9c43 --- /dev/null +++ b/src/data/question-groups/react/content/set-state.md @@ -0,0 +1,17 @@ +`setState` method is asynchronous by nature. It does not immediately mutate the state but creates a pending state transition. Accessing state after calling this method can potentially return the existing value. + +To avoid this, pass a callback function as a second argument to the `setState` method. This callback function will be executed once the state is updated. + +```js +function handleClick() { + // `username` is some state variable + console.log(username); + setUsername('John Doe'); + console.log(username); // still the old value + + // pass a callback function as a second argument + setUsername('John Doe', () => { + console.log(username); // now it will have the updated value + }); +} +``` \ No newline at end of file diff --git a/src/data/question-groups/react/content/synthetic-events.md b/src/data/question-groups/react/content/synthetic-events.md new file mode 100644 index 000000000..807284df5 --- /dev/null +++ b/src/data/question-groups/react/content/synthetic-events.md @@ -0,0 +1,18 @@ +React differs from HTML in that it uses a synthetic event system instead of directly binding to the browser’s native events. This system brings consistency and performance benefits, and it allows React to be agnostic of environments like browser, server, or React Native. + +The events such as `onClick`, `onSubmit`, `onFocus`, etc. are all camel-cased to be consistent with the naming convention in JavaScript. React event handlers are written inside curly braces: + +```jsx +function activateLasers(e) { + e.preventDefault(); + console.log('The button was clicked.'); +} + + +``` + +In this case `activateLasers` is the event handler which will receive a React event object which, also known as a "synthetic event". It conforms to the same standard as the underlying DOM events, but fixes some browser inconsistencies. + +Some React events do not map directly to the browser’s native events. For example in `onMouseLeave`, `e.nativeEvent` will point to a `mouseout` event. If you need the underlying browser event for some reason, read it from `e.nativeEvent`. + +Visit the [React documentation](https://react.dev/reference/react-dom/components/common#react-event-object) for further details. \ No newline at end of file diff --git a/src/data/question-groups/react/react.md b/src/data/question-groups/react/react.md index 7b0642e84..a100949e3 100644 --- a/src/data/question-groups/react/react.md +++ b/src/data/question-groups/react/react.md @@ -21,45 +21,162 @@ questions: - question: What is a React? answer: React, is an open-source JavaScript library for building user interfaces (UIs). It was developed and is maintained by Meta, and is widely used by developers to create interactive and dynamic web applications. topics: - - 'Basics' + - 'Core' - 'Beginner' - question: What are the features of React? answer: Use of Virtual DOM instead of Real DOM, JSX, Server-side rendering, Unidirectional data flow or data binding, Reusable components, etc. topics: - - 'Basics' + - 'Core' - 'Beginner' - question: What is JSX? answer: JSX is a syntax extension to JavaScript and comes with the full power of JavaScript. JSX produces React “elements”. You can embed any JavaScript expression in JSX by wrapping it in curly braces. After compilation, JSX expressions become regular JavaScript objects. topics: - - 'Basics' + - 'Core' - 'Beginner' - question: What is the difference between Real DOM and Virtual DOM? answer: | Virtual DOM is the representation of a UI in the form of a plain javascript object. It is a node tree that lists the elements, their attributes and content as Objects and their properties. Real DOM is the real representation of a UI which can be seen and inspected in the browser. Manipulating the virtual DOM is much faster than real DOM, because nothing gets drawn on the screen. React uses this virtual DOM to figure out the most efficient way to update the browser DOM. topics: - - 'Basics' + - 'Core' - 'Beginner' - question: What is the difference between state and props? answer: | Props are used to pass data from parent to child. They are like function arguments. They are immutable. State is managed within the component and is mutable. topics: - - 'Basics' + - 'State' + - 'Beginner' + - question: Can we change the state of the component directly? + answer: No, we can't change the state of the component directly. State can only be changed by using `setState()` method. Changing the state variable directly won't re-render the component. + topics: + - 'State' + - 'Beginner' + - question: What is the purpose of callback function as an argument of setState()? + answer: set-state.md + topics: + - 'State' - 'Beginner' - question: What is the difference between controlled and uncontrolled components? answer: controlled-vs-uncontrolled.md topics: - - 'Basics' + - 'State' - 'Beginner' - question: What are different options to style a React component? answer: CSS Stylesheets, Inline styles, CSS Modules, Styled Components, CSS in JS libraries, etc. topics: - 'Styling' - 'Beginner' - - question: What are different ways to keep React performant? - answer: 'react-performance.md' + - question: What are Pure Components? + answer: pure-components.md + topics: + - 'Performance' + - 'Intermediate' + - question: What are Synthetic Events in React? + answer: synthetic-events.md + topics: + - 'Events' + - 'Intermediate' + - question: What is the purpose of `key` attribute in React? + answer: The string attribute `key` is a special attribute you need to include when rendering an array of elements. Keys help React identify which items have changed, are added, or are removed. Keys should be given to the elements inside the array to give the elements a stable identity. + topics: + - 'Performance' + - 'Beginner' + - question: What are refs in React? + answer: | + Refs are used to get reference to a DOM node or an instance of a component. They help to access the DOM nodes or React elements created in the render method. + You can also use refs When you want a component to “remember” some information, but you don’t want that information to trigger new renders, you can use a ref. + topics: + - 'Core' + - 'Intermediate' + - question: What is ref forwarding in React? + answer: ref-forwarding.md + topics: + - 'Core' + - 'Intermediate' + - question: What is React Fiber? + answer: | + React fiber is the reconciliation engine that replaced the core algorithm in React v16. It is a rewrite of the core algorithm, responsible for scheduling what gets rendered on screen. It is a set of algorithms for efficiently updating the UI. + Here is a [bit-outdated but quite good article about React Fiber](https://github.com/acdlite/react-fiber-architecture). + topics: + - 'Core' + - 'Advanced' + - question: What is the difference between react and react-dom packages? + answer: | + React is a library for building user interfaces. The package `react` contains only the renderer-agnostic code i.e. the core React library, algorithm for computing changes in the UI and other helpers. . The package `react-dom` contains the code specific to the DOM rendering of React components. + topics: + - 'Core' + - 'Beginner' + - question: What is the difference between class components and function components? + answer: | + Class components let you define your components with the help of classes. You can extend from `React.Component` class to create a component. Class components also allow you to define component level lifecycle methods. + Function components are defined by writing a function which returns a React element. Functional components are the preferred way to write React components. There are no lifecycle methods similar to class components available in functional components; you can use React hooks instead to manage the component lifecycle. + topics: + - 'Core' + - 'Beginner' + - question: What are Higher-Order Components (HOCs)? + answer: | + A higher-order component (HOC) is a function that takes a component and returns a new component. Basically, it's a pattern that is derived from React's compositional nature. + Higher-Order Components are not part of the React API. They are the pattern that emerges from React's compositional nature. + topics: + - 'Core' + - 'Intermediate' + - question: What are React Hooks? + answer: | + Hooks are functions that let you “hook into” React state and lifecycle features from function components. Hooks don't work inside classes — they let you use React without classes. Some common hooks include `useState`, `useEffect`, `useMemo`, `useRef`, `useCallback`, etc. + topics: + - 'Core' + - 'Beginner' + - question: How to render HTML in React? + answer: | + You can use `dangerouslySetInnerHTML` prop to render HTML in React. It is used to set HTML directly from React. You should be careful while using this property as it can cause XSS attacks. + topics: + - 'Core' + - 'Beginner' + - question: What is Context in React? + answer: | + Context provides a way to pass data through the component tree without having to pass props down manually at every level. Context is primarily used when some data needs to be accessible by many components at different nesting levels. + topics: + - 'State' + - 'Intermediate' + - question: What is Reconciliation in React? + answer: | + Reconciliation is the process through which React updates the DOM by comparing the newly returned elements with the previously rendered ones. React updates the DOM when a component's state changes. + topics: + - 'Core' + - 'Intermediate' + - question: What could be the reasons for un-necessary re-renders in React? + answer: re-renders.md topics: - 'Performance' - 'Intermediate' + - question: How does React handle prop drilling, and what are the downsides of excessive prop drilling? + - answer: Prop drilling is the process of passing data from a parent component to deeply nested child components through props. While React doesn't prohibit this, it can lead to code that is hard to maintain and understand. Excessive prop drilling can make it challenging to track data flow and can result in unnecessary re-renders. To mitigate these issues, you can use Context API or state management libraries like Redux. + topics: + - 'Core' + - 'Intermediate' + - question: What is the purpose of the `useEffect` hook in React? + answer: | + The useEffect hook in React is used for performing side effects in functional components. Side effects can include data fetching, DOM manipulation, and subscribing to external data sources. + topics: + - 'Core' + - 'Intermediate' + - question: What is the purpose of the `useContext` hook in React? + answer: | + The useContext hook is used to access and consume context values in functional components. It provides a way to access context data without the need for a context consumer. useContext is particularly useful when you want to access context values in nested components without having to pass props through intermediate components. + topics: + - 'State' + - 'Intermediate' + - question: What is the purpose of the `useMemo` hook in React? + answer: | + The `useMemo` hook is used to memoize the result of a computationally expensive operation in a functional component. It helps optimize performance by caching the result of the operation and returning the cached result on subsequent renders if the dependencies have not changed. This can prevent unnecessary calculations. + topics: + - 'Performance' + - 'Intermediate' + - question: Explain the concept of error boundaries in React. + answer: | + Error boundaries are special React components that catch JavaScript errors during rendering, in lifecycle methods, and during the constructor of whole tree below them. They are used to handle errors gracefully by displaying a fallback UI and preventing the entire application from crashing due to unhandled errors. + topics: + - 'Core' + - 'Advanced' ---