React & Redux Flashcards
What is React?
React is a javascript library that help us to build a complex and interactive web and mobile appication by following a component based approach which help us to build a reusable UI component
What is Redux?
Redux is a predictable state management library for JavaScript applications, commonly used with frameworks like React or Angular. It provides a centralized store to manage the state of an application and ensures that state changes are predictable and traceable.
Key Concepts in Redux:
- Store: The store is a single source of truth that holds the entire application state. It represents the current snapshot of the application data.
- State: The state is the data that drives the application. It is stored within the Redux store and can only be modified through actions.
- Actions: Actions are plain JavaScript objects that represent events or intents to modify the state. They are dispatched to the Redux store and trigger state changes.
- Reducers: Reducers are pure functions that specify how the state should be updated based on the dispatched actions. They take the current state and an action as input and return a new state.
- Dispatch: Dispatch is a method provided by Redux to send actions to the store. It is used to trigger state changes and update the application’s data.
- Middleware: Redux middleware provides a way to extend the functionality of the store and intercept actions before they reach the reducers. It enables tasks like logging, asynchronous operations, and handling side effects.
Advantages of Redux:
- Centralized State: Redux allows for a single source of truth, making it easier to manage and debug the state of an application.
- Predictable State Changes: The use of pure reducers ensures that state changes are predictable and follow a specific pattern, making the application’s behavior more understandable and maintainable.
- Time Travel Debugging: Redux maintains a log of dispatched actions, enabling developers to replay and inspect past state changes, making debugging easier.
- Ecosystem and Tooling: Redux has a vast ecosystem with various tools, middleware, and devtools that enhance development and debugging processes.
- Scalability: Redux is suitable for large-scale applications with complex state management needs, as it provides a structured and scalable approach to handling application state.
How does redux work?
Redux follows a unidirectional data flow pattern to manage the state of an application. Here’s a high-level overview of how Redux works:
- Store: The Redux store is created, which serves as a centralized container for the application state. The store holds the current state and provides methods to dispatch actions and update the state.
- State: The initial state of the application is defined and stored within the Redux store.
- Actions: Actions are plain JavaScript objects that represent events or intents to modify the state. They are dispatched using the store’s dispatch method. Actions typically have a type property that describes the type of action being performed, along with any additional payload data.
- Reducers: Reducers are pure functions responsible for handling actions and updating the state accordingly. They take the current state and an action as input and return a new state. Reducers should not mutate the state directly but instead create a new copy of the state with the necessary updates.
- State Update: When an action is dispatched, Redux passes the action and the current state to the reducers. The reducers evaluate the action type and return a new state based on the action and the current state. Redux merges the new state with the previous state to create the updated state.
- Subscribers: Redux notifies all the subscribers whenever the state is updated. Components that are subscribed to the Redux store can react to state changes and update their UI accordingly.
- UI Rendering: Reacting to state changes, the subscribed components re-render with the updated data from the Redux store, reflecting the new state in the UI.
- Time Travel Debugging: Redux keeps a log of dispatched actions, allowing developers to rewind, replay, and inspect past state changes. This feature, known as time travel debugging, helps in understanding how the state changes over time and aids in debugging complex scenarios.
The unidirectional flow of actions and state updates in Redux provides a predictable and traceable pattern for managing application state. By following this pattern, Redux makes it easier to reason about the state changes and maintain a consistent application state across components. can grab the states from any point
what makes redux so special
Redux offers several key features that make it special and widely adopted in the JavaScript ecosystem:
- Predictable State Management: Redux promotes a predictable state management pattern by enforcing a strict unidirectional data flow. The state is stored in a single store, and updates are made through actions and reducers. This predictability makes it easier to understand and reason about how the state changes over time.
- Centralized State: Redux provides a centralized store that holds the entire application state. This centralized state makes it easier to manage and access the state across different components in the application. It eliminates the need for prop drilling or passing state through multiple levels of components.
- State Mutation Control: Redux emphasizes immutability and discourages directly mutating the state. Reducers, the pure functions responsible for state updates, create new copies of the state with modifications instead of modifying the existing state. This ensures that the state changes are traceable, easy to reason about, and helps prevent unexpected side effects.
- Time Travel Debugging: Redux maintains a log of dispatched actions, allowing developers to rewind, replay, and inspect past state changes. This feature is known as time travel debugging. It provides powerful debugging capabilities, enabling developers to step backward and forward through the state history to understand how the state changes affect the application’s behavior.
- Middleware Support: Redux offers a middleware mechanism that allows developers to add custom logic and behavior between the dispatching of an action and the actual state update. Middleware can be used for tasks such as logging, handling asynchronous operations, or integrating with external services. This extensibility makes Redux adaptable to various use cases and enhances its capabilities.
- Large Ecosystem and Community: Redux has a vast ecosystem with a wide range of tools, extensions, and integrations. It is widely adopted and supported by the JavaScript community, which means you can find numerous resources, tutorials, and community-driven packages to enhance your Redux development experience.
- Scalability: Redux provides a scalable approach to managing state in large and complex applications. By enforcing a clear separation of concerns and a structured pattern for state management, Redux helps maintain code organization and manage complexity as the application grows.
Overall, Redux’s combination of predictable state management, centralized state, time travel debugging, middleware support, and a thriving ecosystem makes it a popular choice for state management in JavaScript applications. It simplifies state management, improves development efficiency, and promotes best practices in handling application state.
Redux setup process
The setup process for Redux involves several steps. Here’s a high-level overview of the Redux setup process:
- Install Redux: Begin by installing the Redux package using a package manager like npm or yarn. Run the following command:
```bash
npm install redux
~~~
- Define Actions: Actions are plain JavaScript objects that describe an event or intent to modify the state. Define your actions by creating action types and corresponding action creator functions. Action types are typically defined as string constants.
```javascript
// actions.js
export const INCREMENT = ‘INCREMENT’;
export const DECREMENT = ‘DECREMENT’;
export const increment = () => {
return {
type: INCREMENT,
};
};
export const decrement = () => {
return {
type: DECREMENT,
};
};
~~~
- Create Reducers: Reducers are pure functions responsible for handling actions and updating the state. Each reducer typically corresponds to a specific portion of the state. Combine multiple reducers into a root reducer using the
combineReducers
utility function from Redux.
```javascript
// reducers.js
import { combineReducers } from ‘redux’;
import { INCREMENT, DECREMENT } from ‘./actions’;
const counterReducer = (state = 0, action) => {
switch (action.type) {
case INCREMENT:
return state + 1;
case DECREMENT:
return state - 1;
default:
return state;
}
};
const rootReducer = combineReducers({
counter: counterReducer,
});
export default rootReducer;
~~~
- Create the Redux Store: The Redux store is created by passing the root reducer to the
createStore
function from Redux. Optionally, you can provide initial state and apply middleware if needed.
```javascript
// store.js
import { createStore } from ‘redux’;
import rootReducer from ‘./reducers’;
const store = createStore(rootReducer);
export default store;
~~~
- Connect Components to the Redux Store: To access the Redux store and state in your components, use the
connect
function from thereact-redux
package. Connect your components to the store, map the state and actions as props, and use them in your components.
```javascript
// Counter.js
import React from ‘react’;
import { connect } from ‘react-redux’;
import { increment, decrement } from ‘./actions’;
const Counter = ({ count, increment, decrement }) => {
return (
<div>
<h2>Counter: {count}</h2>
<button onClick={increment}>Increment</button>
<button onClick={decrement}>Decrement</button>
</div>
);
};
const mapStateToProps = (state) => {
return {
count: state.counter,
};
};
const mapDispatchToProps = {
increment,
decrement,
};
export default connect(mapStateToProps, mapDispatchToProps)(Counter);
~~~
- Provide the Redux Store: Wrap your root component with the
Provider
component fromreact-redux
to provide the Redux store to your application.
```javascript
// App.js
import React from ‘react’;
import { Provider } from ‘react-redux’;
import store from ‘./store’;
import Counter from ‘./Counter’;
const App = () => {
return (
<Provider store={store}>
<Counter></Counter>
</Provider>
);
};
export default App;
~~~
That’s it! With these steps, you have set up Redux in your application. You can now dispatch actions, update the state, and connect your components to the Redux store to access the state and dispatch actions as needed.
What are reducers in redux?
in a redux, they are a pure function that accepts state and action and returns a new state based on the action
Why do we choose react?
React is a popular choice for building user interfaces for several reasons:
- Component-Based Architecture: React follows a component-based architecture, which allows developers to build reusable and modular UI components. Components encapsulate their own logic and state, making it easier to manage and reason about the UI. This approach promotes code reusability, maintainability, and scalability.
- Virtual DOM: React utilizes a virtual DOM, which is an in-memory representation of the actual DOM. This allows React to efficiently update only the necessary parts of the UI when the state changes, resulting in faster rendering and improved performance. The virtual DOM reconciliation algorithm minimizes DOM manipulations, leading to efficient and optimized UI updates.
- Declarative Syntax: React uses a declarative syntax, where developers describe the desired UI state based on the application’s current state. Instead of manually manipulating the DOM, you define how the UI should look at any given moment, and React takes care of updating the actual DOM accordingly. This makes code easier to understand, debug, and maintain.
- One-Way Data Flow: React follows a unidirectional data flow, where data is passed down from parent components to child components. This makes it easier to track and manage data flow in the application, reducing the likelihood of bugs caused by unexpected state changes. It also promotes a more predictable and stable application behavior.
- Rich Ecosystem: React has a vast and active ecosystem with numerous libraries, tools, and community support. This ecosystem provides a wide range of solutions and extensions for various use cases, making development more efficient and accelerating the process of building complex applications.
- Community and Industry Adoption: React is widely adopted and has a large and active developer community. This means there are abundant resources, tutorials, and community-driven projects available for learning and problem-solving. React is also used by many prominent companies and organizations, making it a valuable skill for job opportunities.
- Cross-Platform Development: React can be used to build applications not only for the web but also for mobile platforms using frameworks like React Native. This allows developers to leverage their React skills and codebase to develop native-like mobile applications for iOS and Android platforms.
Overall, React offers a combination of component-based architecture, virtual DOM efficiency, declarative syntax, one-way data flow, a rich ecosystem, community support, and cross-platform capabilities, making it a compelling choice for building interactive and scalable user interfaces.
What are the major features of react?
React has several major features that make it a popular and powerful JavaScript library for building user interfaces. Here are some of the key features of React:
- Component-Based Architecture: React follows a component-based architecture, allowing developers to build reusable and modular UI components. Components in React encapsulate their own logic, state, and rendering, making it easier to manage and reuse code.
- Virtual DOM: React utilizes a virtual DOM, which is an in-memory representation of the actual DOM. The virtual DOM allows React to efficiently update only the necessary parts of the UI when the state changes. This results in faster rendering and improved performance compared to directly manipulating the real DOM.
- JSX: React uses JSX (JavaScript XML), which is a syntax extension that allows you to write HTML-like code within JavaScript. JSX makes it easier to define the structure and composition of UI components directly in the code, enhancing readability and enabling a seamless combination of HTML and JavaScript.
- One-Way Data Flow: React follows a unidirectional data flow, also known as one-way data binding. Data flows down from parent components to child components, making it easier to track and manage data flow in the application. This promotes better control over the application’s state and reduces unexpected side effects.
- React Hooks: Introduced in React 16.8, Hooks allow functional components to have state and lifecycle features previously only available in class components. Hooks provide a more concise and readable way to manage state and perform side effects in functional components, making them easier to write, test, and maintain.
- Declarative Syntax: React uses a declarative syntax, where developers describe the desired UI state based on the application’s current state. Instead of manually manipulating the DOM, you define how the UI should look at any given moment, and React takes care of updating the actual DOM accordingly. This makes code easier to understand, debug, and maintain.
- React Router: React Router is a popular routing library for React applications. It allows you to implement client-side routing, enabling navigation between different views or pages within a single-page application. React Router provides a declarative way to define routes and handle navigation, making it easier to build complex multi-page applications.
- Server-Side Rendering: React supports server-side rendering (SSR), which means that you can render React components on the server and send the pre-rendered HTML to the client. SSR can improve initial page load times, enable better search engine optimization (SEO), and enhance the overall user experience.
These are some of the major features that make React a powerful and flexible library for building user interfaces. React’s component-based architecture, virtual DOM, JSX syntax, one-way data flow, React Hooks, and other features contribute to its popularity and wide adoption among developers.
What is Virtual DOM? How does the virtual DOM work?
The Virtual DOM (VDOM) is a concept used by React to optimize the rendering of components in a web application. It is an abstraction of the real DOM (Document Object Model) and acts as a lightweight copy or representation of the actual DOM tree.
Here’s how the Virtual DOM works in React:
- Initial Rendering: When a React component is initially rendered or updated, it generates a virtual representation of the component’s UI structure, known as a Virtual DOM tree. This Virtual DOM tree is created using plain JavaScript objects and is stored in memory.
- Diffing: Whenever there is a change in the component’s state or props, React generates a new Virtual DOM tree for the updated component. The new Virtual DOM tree is then compared to the previous Virtual DOM tree using a process called “diffing” or “reconciliation.”
- Efficient Updates: During the diffing process, React efficiently compares the new Virtual DOM tree with the previous one and identifies the minimal set of changes needed to update the actual DOM. Instead of updating the entire DOM tree, React identifies only the specific parts of the tree that require modification.
- Batched Updates: React performs updates in a batched manner. It batches multiple state changes together and applies them in a single pass to minimize the number of DOM manipulations. This helps to improve performance by reducing the browser’s reflow and repaint operations.
- Reconciliation: Once the minimal set of changes is determined, React updates the actual DOM by applying only the necessary modifications. It efficiently adds, updates, or removes DOM nodes based on the differences identified during the diffing process.
- Efficient Rendering: By using the Virtual DOM and performing diffing and batched updates, React optimizes the rendering process. It ensures that only the necessary changes are applied to the actual DOM, resulting in faster rendering and improved performance.
The Virtual DOM provides an abstraction layer that allows React to efficiently update the user interface without directly manipulating the real DOM. It minimizes the number of costly DOM operations and ensures that updates are applied in an optimized manner, leading to a smoother and more efficient rendering process.
By using the Virtual DOM, React can provide a declarative programming model where developers describe the desired UI state, and React takes care of efficiently updating the actual DOM to reflect that state. This abstraction allows developers to focus on building the UI logic and application features without worrying about the low-level DOM manipulation details.
what is JSX?
JSX (JavaScript XML) is a syntax extension used by React that allows you to write HTML-like code directly within JavaScript. It provides a convenient and expressive way to define the structure and composition of React components.
state vs props
In React, both state and props are used to manage and pass data to components, but they serve different purposes.
State:
- State is an internal data storage mechanism within a component.
- State is mutable and can be changed using the setState()
method.
- State is local to the component where it is defined and cannot be accessed or modified by other components.
- State is typically used to manage and represent data that can change over time, such as user input, form values, or component-specific data.
- State updates trigger a re-render of the component, allowing the UI to reflect the updated state.
Props:
- Props (short for properties) are read-only data passed from a parent component to a child component.
- Props are immutable and cannot be modified directly by the child component. They are passed down from the parent component and are considered “owned” by the parent component.
- Props are used to configure and customize child components based on the parent component’s data or behavior.
- Props provide a way to pass data and communicate between components in a unidirectional flow.
- Changes to props in the parent component can trigger re-renders of the child components with the updated props, allowing for dynamic and flexible composition of components.
To summarize, state is internal to a component and manages its own data, while props are passed from a parent component and used to configure and customize child components. State is mutable and managed within the component, while props are read-only and owned by the parent component. Both state and props play crucial roles in managing and updating the data and behavior of React components.
what does lifting state up mean? and why do we do it?
Lifting state up in React refers to the process of moving the state from a child component to its parent component. Instead of managing the state locally within the child component, the state is lifted up to a common ancestor component that controls the state for multiple child components.
The main reasons for lifting state up are:
- Centralized State Management: By lifting state up, you centralize the management of state in a single parent component. This makes it easier to track and manage the state as the application grows and becomes more complex. It provides a clear and centralized place to handle state changes and ensures consistency across related components.
- Shared State: Lifting state up allows multiple child components to access and share the same state. This enables sibling components or deeply nested components to communicate and synchronize their data through the shared state. It promotes a more cohesive and interconnected component structure.
- Avoiding Prop Drilling: Prop drilling occurs when you need to pass down props through multiple intermediate components to reach a deeply nested child component that needs the data. By lifting the state up, the shared state can be accessed directly by the child components without the need for prop drilling, which improves code readability and maintainability.
- Separation of Concerns: Lifting state up helps to separate the concerns of data management and presentation. The parent component becomes responsible for managing the state, while the child components focus on rendering the UI and responding to user interactions. This separation enhances the reusability and testability of the components.
- Performance Optimization: In some cases, lifting state up can lead to performance optimizations. If multiple child components need access to the same state, lifting it up avoids redundant state duplication in each child component. It reduces the memory footprint and ensures that updates to the shared state trigger a single re-render at the parent level, rather than multiple re-renders at each child component.
Overall, lifting state up promotes better component design, simplifies data flow, and improves the overall structure and maintainability of React applications. It allows for more effective state management and facilitates communication between components, leading to more robust and scalable code.
Why do we set key property when we map over an array in react?
In React, when you map over an array to create a list of elements, it is recommended to assign a unique key
property to each rendered element. The key
property is a special attribute that helps React identify and track each element in the array during the reconciliation process.
Here’s why setting a key
property is important:
- Efficient Updates: The
key
property helps React efficiently update the list of elements when the underlying data changes. When a new array is rendered, React compares thekey
of each element in the new array with thekey
of the corresponding element in the previous array. This enables React to determine if an element was added, removed, or re-ordered. - Virtual DOM Reconciliation: The
key
property plays a crucial role in the reconciliation algorithm used by React’s Virtual DOM. When a component’s state changes or the array being mapped over is updated, React uses thekey
property to quickly identify the elements that have changed. This allows React to update only the necessary parts of the DOM, improving performance. - Preserving Component State: The
key
property is used by React to preserve the state of individual components within a list. If a component has a uniquekey
, React can retain the component’s state even when the list is re-rendered. Without thekey
, React would treat the component as a new instance and reset its state, leading to potential data loss or incorrect behavior. - Stable Element Identity: The
key
property helps ensure stable element identity within a list. When a list is re-rendered, React uses thekey
to match elements between the old and new lists. Without a uniquekey
, React would rely on positional index matching, which can cause issues if the order of elements changes or new elements are inserted or removed.
It’s important to note that the key
property should be a unique identifier within the scope of the list. Commonly used identifiers are unique IDs or key values from the data being mapped. It is recommended to avoid using positional indices (index
from the map
function) as key
values, as it can lead to unexpected behavior and performance issues.
By setting a unique key
property, you provide React with the necessary information to efficiently update and reconcile the list of elements, ensuring accurate rendering and preserving component state.
what are the core principles of redux?
- single source of truth - the global state of the application is stored in an object tree with a single store
- State is read only- the only way to change the state is by emitting an action, an object describing what happened
- Changes are made with pure functions
How do we make AJAX requests in redux?
By using middlewares we have 3 middlewares to use
1. Redux Promise middleware - the action creator returns a promise inside the action, and the promise must be under the payload key in the action
- Redux Thunk middleware - the action creator returns function that takes on argument dispatch
- Redux Saga middleware - the AJAX calls in the saga instead of the action creator