React Basics III Flashcards

1
Q

What is Prop Drilling and How to Avoid it?

A

Prop drilling in React refers to the process of passing data (props) from a parent component down to deeply nested child components through multiple intermediate components, even if those intermediate components do not directly use the data. This can lead to unnecessary complexity and reduced maintainability.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

How to Avoid Prop Drilling?

A

Using Context API
Using Custom Hooks

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Using Context API

A

createContext() creates a context (UserContext) to share data across components.

The App component uses UserContext.Provider to pass userName (‘geeksforgeeks’) as the context value.

ParentComponent and its children (ChildComponent,

GrandChildComponent) are wrapped by the provider.

GrandChildComponent accesses the context value using useContext(UserContext).

The value (‘geeksforgeeks’) is displayed in a <p> tag as “Hello, geeksforgeeks!”.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Using Custom Hooks

A

createContext() creates UserContext to share data across components.

useUser() is a custom hook wrapping useContext(UserContext) for simplicity.

App provides the context value (“GeeksforGeeks”) using
UserContext.Provider.

Nested components (Component, Child, Grand) inherit the context value.

Grand accesses the value via useUser() and displays “Hello, GeeksforGeeks!

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

React Lists

A

To render a list in React, we will use the JavaScript array map function. We will iterate the array using** map()** and return the required element in the form of JSX to render the repetitive elements.

Use a unique identifier like id when available.
Avoid using array indexes as keys unless necessary (e.g., static lists without reordering).

ONLY FOR STATIC LIST INDEX CAN BE KEYS!

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What is Context API?

A

Context API is used to pass global variables anywhere in the code without the prop drilling. It helps when there is a need for sharing state between a lot of nested components. It is light in weight and easier to use, to create a context just need to call React.createContext(). No need to install other dependencies or third-party libraries like redux for state management.

-no middlewares for async tasks
-no dev tools
-weak performance- re-render every time

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Why is Context API used?

A

Context API solves the problem of prop drilling in React. Prop Drilling occurs when data is to be passed between multiple layers before finally sending it to the required component. This makes the application slower. This problem is solved by Context API as it creates global variables to be used throughout the application without any middle components involved. It is also easier to use than React Redux

To work with Context API we need React.createContext. It has two properties Provider and Consumer. The Provider acts as a parent it passes the state to its children whereas the Consumer uses the state that has been passed.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Benefits of Context API over React Redux

A

In Redux we have to manipulate or update multiple files to add even a single feature but in Context it can be done in much lesser lines of code

One way data binding in React is maintained using Context whereas Redux violates it.

Multiple stores/contexts can be created using Context whereas Redux creates just a single store

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What is Redux?

A

Redux is a predictable state container for JavaScript applications. It helps manage an application’s state in a centralized way, making it easier to maintain and debug, especially as the app grows in complexity.

It is based on three fundamental principles:

Single Source of Truth: The entire application state is stored in a single JavaScript object called the store.

State is Read-Only: The only way to change the state is by dispatching an action that describes the change.

Changes are Made with Pure Functions: Changes to the state are made using reducers, which are pure functions that take the previous state and an action, and return the new state.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Core Concepts of React-Redux

A
  1. Store
    The store is a centralized object that holds the application state. It is the only place where the state can be modified.
  2. Actions
    An action is a plain JavaScript object that describes a change in the application state. It must have a type property and can optionally include a payload.
  3. Reducers
    A reducer is a pure function that specifies how the application’s state changes in response to an action. It takes the current state and an action as arguments and returns a new state.
  4. Dispatch
    The dispatch function is used to send an action to the Redux store, triggering the reducer to process the state change.
  5. Selectors
    A selector is a function that retrieves specific pieces of state from the Redux store. It helps to abstract the state retrieval process, making it easier to access state in a more manageable way.
  6. Provider
    The Provider component makes the Redux store available to all the components in the application. It should wrap the entire application so that any component can access the store.
  7. connect()
    connect() is a function provided by React-Redux to connect React components to the Redux store. It allows the components to access the state and dispatch actions.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

How React-Redux Works

A
  1. Setting Up the Store
  2. Dispatching Actions
  3. Reducers Update the State
  4. Connecting Components with connect()
  5. Using Provider to Make Store Accessible
  6. Re-Renders and Reactivity
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What are Hooks in React

A

React Hooks are functions that allow functional components in React to manage state, handle side effects, and access other React features without needing class components. They provide a simpler and more efficient way to manage component logic.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Types of React Hooks

A
  1. State Hooks
  2. Context Hooks
  3. Effect Hooks
  4. Performance Hook
  5. Resource Hooks(useFetch)
  6. Other Hooks
  7. Custom Hooks
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q
  1. State Hooks
A

State hooks, specifically useState and useReducer, allow functional components to manage state in a more efficient and modular way.

They provide an easier and cleaner approach to managing component-level states in comparison to class components.

useState: The useState hook is used to declare state variables in functional components. It allows us to read and update the state within the component.

const [state, setState] = useState(initialState);

state: The current value of the state.

setState: A function used to update the state.

initialState: The initial value of the state, which can be a primitive type or an object/array

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

useReducer

A

useReducer: The useReducer hook is a more advanced state management hook used for handling more complex state logic, often involving multiple sub-values or more intricate state transitions.

const [state, dispatch] = useReducer(reducer, initialState);
state: The current state value.

dispatch: A function used to dispatch actions that will update the state.

reducer: A function that defines how the state should change based on the dispatched action.

initialState: The initial state value.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q
  1. Context Hooks
A

The useContext hook in React is a powerful and convenient way to consume values from the React Context API in functional components. It allows functional components to access context values directly, without the need to manually pass props down through the component tree

const contextValue = useContext(MyContext);

const contextValue = useContext(MyContext);

The useContext hook takes a context object (MyContext) as an argument and returns the current value of that context.

The contextValue will hold the value provided by the nearest <MyContext.Provider> in the component tree.</MyContext.Provider>

17
Q

Effect Hooks

A

Effect hooks, specifically useEffect, useLayoutEffect, and useInsertionEffect, enable functional components to handle side effects in a more efficient and modular way.

useEffect: The useEffect hook in React is used to handle side effects in functional components. It allows you to perform actions such as data fetching, DOM manipulation, and setting up subscriptions, which are typically handled in lifecycle methods like componentDidMount or componentDidUpdate in class components.

18
Q

Performance Hook

A

Performance Hooks in React, like useMemo and useCallback, are used to optimize performance by avoiding unnecessary re-renders or recalculations.

useMemo: useMemo is a React hook that memoizes the result of an expensive calculation, preventing it from being recalculated on every render unless its dependencies change. This is particularly useful when we have a computation that is expensive in terms of performance, and we want to avoid recalculating it on every render cycle.

useCallback: The useCallback is a React hook that helps to memoize functions, ensuring that a function is not redefined on every render unless its dependencies change. This is particularly useful when passing functions as props to child components, as it prevents unnecessary re-renders of those child components

19
Q

Resource Hooks(useFetch)

A

The useFetch is typically a custom hook used for fetching data from an API. It is implemented with useEffect to fetch data when the component mounts or when dependencies change.

Synatx

const { data, loading, error } = useFetch(url);
useFetch is a custom hook for fetching data from a given URL.
It uses useEffect to fetch data when the URL changes and updates the data state.

20
Q

Other Hooks

A

React offers additional hooks for specific use cases

useReducer: For complex state management.
useImperativeHandle: Customizes the instance value exposed by useRef.
useLawetEffect: Like useEffect but fires synchronously after DOM updates.

21
Q

What is the useState Hook in React?

A

The useState Hook is a built-in React Hook that allows functional components to manage state. It returns an array with two elements: the current state value and a function to update that state.

22
Q

How do I update the state using useState?

A

State updates in useState can be done by calling the setter function with a new value or by passing a function that receives the previous state.

23
Q

Does useState merge the state like setState in class components?

A

No, useState does not merge the state automatically. If the state is an object, you must manually merge it.

24
Q

Can useState accept a function as an initial state?

A

Yes, if the initial state needs computation, you can pass a function that returns the initial value

25
Q

What is React Events?

A

React events are functions that get triggered in response to user interactions or other actions in the browser.

They are similar to standard DOM events but have a consistent, cross-browser interface in React. React events use camelCase naming conventions and are attached to JSX elements as attributes.

onClick

This event is used to detect mouse clicks in the user interface.

onChange

This event is used to detect a change in the input field in the user interface.

onSubmit

This event fires on the submission of a form in the user interface and is also used to prevent the default behavior of the form.

onKeyDown

This event occurs when the user press any key from the keyboard.

onKeyUp

This event occurs when the user releases any key from the keyboard.

onMouseEnter

This event occurs when the ouse enters the boundary of the element

26
Q

How do React events differ from native DOM events?

A

React events are synthetic events, which means they provide a consistent API across different browsers. They are optimized for performance using event delegation.

27
Q

Why is bind(this) needed in class components?

A

In JavaScript, class methods are not bound to the instance by default. Using bind(this) ensures that this refers to the component instance inside event handlers.

28
Q

Can I use event listeners like addEventListener in React?

A

Yes, but it’s usually unnecessary because React provides built-in event handling. If needed, you can use componentDidMount():

29
Q

What is the React Lifecycle?

A

The React lifecycle refers to the different phases a component goes through during its time in a React application. These phases allow you to run specific code at key moments in a component’s life, such as when it’s created, updated, or removed from the screen.

30
Q

Here are the three main phases of the React component lifecycle

A

Mounting: Initializes, renders, and mounts the component (componentDidMount()).

Updating: Handles state/prop changes, re-renders, and updates (componentDidUpdate()).

Unmounting: Cleans up before removal (componentWillUnmount()).

31
Q
  1. Mounting
A

Mounting refers to the process of creating and inserting a component into the DOM for the first time in a React application. During mounting, React initializes the component, sets up its internal state (if any), and inserts it into the DOM.

constructor
getDerivedStateFromProps
render()
componentDidMount()

32
Q
  1. Updation
A

Updating refers to the process of a component being re-rendered due to changes in its state or props. This phase occurs whenever a component’s internal state is modified or its parent component passes new props. When an update happens, React re-renders the component to reflect the changes and ensures that the DOM is updated accordingly.

getDerivedStateFromProps
setState() Function
shouldComponentUpdate()
getSnapshotBeforeUpdate() Method
componentDidUpdate()

33
Q
  1. Unmounting
A

This is the final phase of the lifecycle of the component, which is the phase of unmounting the component from the DOM. The following function is the sole member of this phase.

componentWillUnmount()
This function is invoked before the component is finally unmounted from the DOM, i.e., this function gets invoked once before the component is removed from the page, and this denotes the end of the lifecycle.