NgRx Top Interview Questions and Answers You should know

NgRx Top Interview Questions and Answers
First I would like to thank the NgRx team for such a great library and for the nice documents. Below answers are taken by NgRx official doc.
Go to Docs: https://ngrx.io/docs
π‘ What is NgRx?
NgRx is a library for building reactive applications in Angular, inspired by Redux
, a very useful and predictable state management container for JavaScript apps.
It was developed by Rob Wormald
, an Angular Developer Advocate in 2013.
β It provides great features –
- Manage application Global (Centralized) and Local state.
- Promote a clean and dump component architecture.
- Entity collection management.
- Integration with the Angular Router.
- Developer Tooling
π‘ Why use NgRx Store for State Management?
NgRx Store provides state management for creating highly maintainable applications through the use of a single state. It provides actions in order to express state changes. In case, some components don’t need a wide state, ngRx uses ComponentStore
which provides a solution for local state management.
π‘ When choosing ngRx?
In particular, you might use NgRx when you build an application with a lot of user interactions and multiple data sources, or when managing a state in services that is no longer sufficient.
The store is built on a single, immutable data structure. ngRx provides selector functions that optimize retrieving data from your state. ngRx provides Effects and Stores for interactions with external resources like network requests.
Read here for more details.
π‘ Explain the Core Concept of ngRx.
Store
– We can say it database of the application. It is immutable and only altered by actions.-
Actions
– dispatched from components and services. -
Reducers
– Reducers are pure functions that are responsible for state changes. It takes the current state and the latest action to create a new state. Meta-reducers
– These are similar to middleware used in Redux. It allows us to pre-process actions before normal reducer functions are called.- Selectors – These are also pure functions to obtain slices of the store state instead of the full state.
Effects
– Without ngRx, components are responsible to connect with external APIs using services. So ngRx effects provide a way to interact with external sources (services, network requests, web sockets, etc.) and isolate them from the component.
π‘ Explain ngRx Life Cycle.
Please see the first flow diagram of this post to understand the lifecycle.
π‘ What is the state “ select “ function?
we can access one of the states by using the select function. The select function picks the desired state from the store and returns an Observable.
this.store.select('products').subscribe((state => this.products = state));
π‘ What is createAction function in ngRx and how it differs from the old way to create Actions?
The createAction
is a factory function that returns an object of the Action interface when called.
β Without createAction –
import { Action } from '@ngrx/store'; export enum ProductActionTypes = { AddProduct = '[Product] Add Product', RemoveProduct = '[Product] Remove Product', } export class AddProduct implement Action { readonly type = ProductActionTypes.AddProduct; constructor(public payload: any){} }
β New way to create actions –
import { createAction, props } from '@ngrx/store'; export const addProduct = createAction('[Product] Add Product'); export const removeProduct = createAction('[Product] Remove Product', props<{productId: number}>());
π‘ How can we pass extra information with Actions?
// Action Interface interface Action { type: string; }
Above is the interface of Actions. We can add properties to an action to provide additional context or metadata for an action.
{ type: '[Login Component] Login', username: string; password: string; }
import { createAction, props } from '@ngrx/store'; export const login = createAction( '[Login Component] Login', props<{ username: string; password: string }>() ); // call store.dispatch(login({ username: username, password: password }));
π‘ Is Reducer work synchronously or asynchronously?
Reducers
are pure functions that return the same output for a given input without any side effects. reducers handle state transition synchronously.
π‘ Explain a new way to create a reducer function?
ngRx introduced a new “createReducer
” function that allows creating a reducer without a switch statement. It uses the "on" function
to make a distinction between the action types and returns a new reference of the state.
β old way —-> We use a switch statement.
import {ProductActionTypes, ProductActions} from './actions'; export const initialState = []; export function reducer(state = initialState, action: ProductActions) { switch (action.type) { case ProductActionTypes.AddProduct: return [...state, action.payload] case ProductActionTypes.RemoveProduct: let product = action.payload; return state.filter((el)=>el.id != product.id) default: return state; } }
β New way with createReducer function –
import { Action, createReducer, on } from '@ngrx/store'; export const initialState: State = { quantity: 0, productName: 0, }; export const createReducer(initialState, on(ProductActionTypes.AddProduct, state => ({...state, quantity: state.quantity + 1}) ), on(ProductActionTypes.RemoveProduct, (state, {product} => ({...state, id: state.ids.filter(id => id !== product.id)})) ) )
π‘ What is Memoization in ngRx?
Memoization
is an optimization technique that is used to speed up computer programs by storing the results of expensive functions & return the same cached result when that function is called again with the same input parameters.
In ngRx, Selectors
provides a feature of memoization using createSelector & createFeatureSelector functions that keep track of invoked functions with the latest arguments. Because selectors are pure functions, it returns the last result when reinvoking your selector function with the same arguments. It is very helpful in terms of application performance.
import { createSelector } from '@ngrx/store';
π‘ What are the advantages of Effects in ngRx?
Effects
isolate side effects from components and make them pure components that are responsible for only select state and dispatch actions.- Effects are long-running services or operate big computation that listens to an observable of every action dispatched from the Store.
- Effects handle tasks, which are synchronous or asynchronous and return a new action.
@Injectable() export class ItemEffects { loadItems$ = createEffect(() => this.actions$.pipe( ofType('[Item Component] Load Items'), mergeMap(() => this.itemService.getAll() .pipe( map(items => ({ type: '[Items API] Items Loaded', payload: items })), catchError(() => EMPTY) )) ) ); constructor( private actions$: Actions, private itemService: ItemService ) {} }
π‘ How to register Effects in the app.module?
import { EffectsModule } from '@ngrx/effects'; import { ProductEffects } from './effects/product.effects'; @NgModule({ imports: [ EffectsModule.forRoot([ProductEffects]) ], }) export class AppModule {}
β Note:
Effects start running immediately after the AppModule is loaded to ensure they are listening for all relevant actions as soon as possible.
- Insert node in Linked list | Algorithm | JavaScript
- Insertion Sort in data structure | Algorithm with Examples
- Selection Sort Algorithm & K’th Largest Element in Array
- Quick Sort Algorithm with example | Step-by-Step Guide
- Dependency Inversion Principle with Example | Solid Principles
- Object-Oriented Programming | Solid Principles with Examples
- ASCII Code of Characters | String Operations with ASCII Code
- Negative Binary Numbers & 2’s Complement | Easy explanation
- Factors of a Number | JavaScript Program | OptimizedΒ Way
- LeetCode – Game of Life Problem | Solution with JavaScript
- Fibonacci series using Recursion | While loop | ES6 Generator
- JavaScript Coding Interview Question & Answers
- LeetCode – Coin Change Problem | Dynamic Programming | JavaScript
- HackerRank Dictionaries and Maps Problem | Solution with JavaScript
- React Redux Unit Testing of Actions, Reducers, Middleware & Store
- Micro frontends with Module Federation in React Application
- React Interview Question & Answers – Mastering React
- Top React Interview Question & Answer | React Routing
- React Interview Questions and Answers | React hooks
- Higher Order Component with Functional Component | React JS
- Top React Interview Questions and Answers | Must Know
- Interview Question React | Basics for Freshers and Seniors
- Cyber Security Fundamental Questions & Answers You must know
- Application & Web Security Interview Questions & Answers
- Top Scrum Master and Agile Question & Answers 2022
- Trapping Rain Water Leetcode Problem Solution
- Array Representation of Binary Tree | Full Tree & Complete Binary Tree
- Graphs in Data Structure, Types & Traversal with BFS and DFS, Algorithms
- Traversing 2 D array with BFS & DFS Algorithm in JavaScript
- Time Complexity & Calculations | All You should know
- Backspace String Compare Leetcode Problem & Solution
- Angular Interview Questions & Answers 2021 – Part 3 – JS Mount
- Why Angular is a Preferred Choice for Developers? Top Features
- Angular Interview Questions & Answers You should know Part 2
- Top 30 JavaScript Interview Questions and Answers for 2021
- React JS Stripe Payment Gateway Integration with Node | Step by Step Guide
- Create Year Month & Date dropdown List using JavaScript & JQuery
- Create Custom QR Code Component using QR Code Styling in React JS
- How to create a common Helper class or util file in React JS
- React Build Routing with Fixed Header and Navigation | React Router Tutorial
- React Create Dashboard Layout with Side Menu, Header & Content Area
- Web Application Security Best Practices | Top Tips to Secure Angular App
- HTML Form with Pure CSS & JavaScript | Custom Radio and Checkbox
- NgRx Top Interview Questions and Answers You should know
- Top 40 Awesome CSS Interview Questions & Answers You should know | CSS Tutorial
- Tips to Boost Angular App Performance | Web page Speed Optimization
- JavaScript Rotate 2D matrix 90 degrees clockwise | Top Interview Question
- HashTable Data Structure in JavaScript with Add Delete & Search Algorithms
- Trie Data Structure – Insert Search Delete & Print Program with JavaScript
- Top JavaScript Commonly asked Algorithms in Interview
NgRx Top Interview Questions and Answers