Skip to main content

Create 250 .NET Core Interview Question and Answer

 

C# Interview Questions (50)

1. What is C#?

Answer: C# is a modern, object-oriented programming language developed by Microsoft, running on the .NET framework. It’s used for building Windows applications, web services, and games via Unity.

2. Explain value types vs. reference types.

Answer: Value types (e.g., int, struct) store data directly in memory, while reference types (e.g., class, string) store references to memory locations. Value types are stack-allocated; reference types are heap-allocated.

3. What is boxing and unboxing?

Answer: Boxing converts a value type to a reference type (e.g., int to object). Unboxing converts a reference type back to a value type. Both impact performance due to memory overhead.

4. What is the static keyword?

Answer: static declares members (methods, fields) that belong to the type itself, not instances. A static class cannot be instantiated.

5. Explain delegates.

Answer: Delegates are type-safe function pointers that reference methods. They enable events and callbacks.

6. What are generics in C#?

Answer: Generics allow classes, methods, or interfaces to operate with any data type (e.g., List<T>), ensuring type safety and reducing code duplication.

7. What is async/await?

Answer: async marks a method as asynchronous, and await pauses execution until the awaited task completes, non-blocking the thread.

8. Explain the difference between abstract and interface.

Answer: abstract classes can have implementations; interfaces define contracts (no implementations before C# 8). A class can implement multiple interfaces but inherit only one abstract class.

9. What is LINQ?

Answer: Language Integrated Query (LINQ) provides query capabilities directly in C# for collections, databases, and XML using a unified syntax.

10. How does garbage collection work?

Answer: The .NET garbage collector (GC) automatically reclaims memory by tracking and destroying unreachable objects, using generations (Gen 0, 1, 2) for optimization.

11. What is the using statement?

Answer: using ensures IDisposable objects (e.g., file handles) are disposed of properly, even if exceptions occur.

12. Explain exception handling.

Answer: Use try, catch, finally, and throw to handle runtime errors. finally executes regardless of exceptions.

13. What is a Tuple?

Answer: A Tuple represents a fixed-size collection of elements of possibly different types (e.g., (int, string)).

14. What is the difference between const and readonly?

Answer: const is compile-time constant; readonly is runtime and can be set in constructors.

15. What is reflection?

Answer: Reflection inspects metadata (types, methods) at runtime, enabling dynamic type manipulation.

16. Explain StringBuilder.

Answer: StringBuilder efficiently modifies strings without creating new instances, unlike immutable string.

17. What is the var keyword?

Answer: var enables implicit typing (compiler infers type from initialization). Requires initialization.

18. What is an Action and Func?

Answer: Action represents a method with no return type; Func returns a value (e.g., Func<int, int>).

19. Explain IEnumerable vs. IQueryable.

Answer: IEnumerable works in-memory; IQueryable queries remote data sources (e.g., databases) with deferred execution.

20. What is a Task?

Answer: Task represents an asynchronous operation, part of the Task Parallel Library (TPL).

21. What is dependency injection (DI)?

Answer: DI is a design pattern where dependencies are "injected" into a class, improving testability and modularity.

22. Explain lock statement.

Answer: lock ensures only one thread accesses a code block at a time, preventing race conditions.

23. What is the difference between == and Equals()?

Answer: == compares references by default (overloadable); Equals() checks value equality (virtual method).

24. What is the dynamic keyword?

Answer: dynamic bypasses static type checking, resolved at runtime (DLR).

25. Explain partial classes.

Answer: Partial classes split a class definition across multiple files, used for auto-generated code (e.g., UI designers).

26. What is an extension method?

Answer: Extension methods add functionality to existing types without inheritance, using this in the first parameter.

27. What is the difference between Array and ArrayList?

Answer: Array is fixed-size and type-safe; ArrayList is dynamic but stores objects (requires boxing/unboxing).

28. Explain yield keyword.

Answer: yield returns elements one at a time in an iterator block, enabling lazy evaluation.

29. What is the volatile keyword?

Answer: volatile ensures a field is read/written directly from memory, preventing compiler optimizations in multithreading.

30. What is the difference between Stack and Heap?

Answer: Stack stores value types and references (LIFO); heap stores reference-type objects (managed by GC).

31. Explain params keyword.

Answer: params allows a method to accept a variable number of arguments (e.g., void Method(params int[] values)).

32. What is the default keyword?

Answer: default(T) returns the default value for type T (e.g., 0 for int, null for objects).

33. What is a Nullable type?

Answer: Nullable<T> (or T?) allows value types to hold null (e.g., int?).

34. Explain nameof operator.

Answer: nameof returns the string name of a variable/type, reducing magic strings.

35. What is the difference between Task.Run and Task.Factory.StartNew?

Answer: Task.Run is simplified for Task; StartNew offers advanced options (e.g., scheduler, cancellation).

36. What is the async modifier?

Answer: async enables await in methods, returning Task/Task<T> or void.

37. Explain MemoryMappedFile.

Answer: MemoryMappedFile maps file contents to memory for efficient large-file access.

38. What is the unsafe context?

Answer: unsafe allows pointer operations for low-level code (e.g., interop).

39. Explain Lazy<T>.

Answer: Lazy<T> delays object initialization until first access, improving startup performance.

40. What is the difference between Dispose and Finalize?

Answer: Dispose is explicit cleanup (via IDisposable); Finalize (destructor) is implicit GC cleanup.

41. What is the Interlocked class?

Answer: Interlocked provides atomic operations (e.g., Increment) for thread safety.

42. Explain ConcurrentDictionary.

Answer: ConcurrentDictionary is a thread-safe dictionary for parallel operations.

43. What is the difference between struct and class?

Answer: struct is a value type (stack-allocated); class is a reference type (heap-allocated).

44. What is the where clause in generics?

Answer: where constrains generic types (e.g., where T : new()).

45. Explain Expression<TDelegate>.

Answer: Expression represents code as data, enabling LINQ providers to translate queries (e.g., to SQL).

46. What is the CallerMemberName attribute?

Answer: Automatically obtains the calling method/property name (used in INotifyPropertyChanged).

47. What is the difference between Task.WaitAll and Task.WhenAll?

Answer: WaitAll blocks threads; WhenAll returns a Task for non-blocking async.

48. Explain Span<T>.

Answer: Span<T> provides a type-safe view over contiguous memory (stack/heap) without allocation.

49. What is the IAsyncEnumerable interface?

Answer: Enables asynchronous iteration over collections (e.g., await foreach).

50. What is C# 9’s record type?

Answer: record is a reference type with built-in value-based equality and immutability.


LINQ Interview Questions (50)

1. What is LINQ?

Answer: Language Integrated Query (LINQ) provides a unified syntax for querying data from collections, databases, XML, and more.

2. Explain deferred execution.

Answer: LINQ queries execute when enumerated (e.g., foreach), not when defined. Enables query composition.

3. What is the difference between IEnumerable and IQueryable?

Answer: IEnumerable executes in-memory; IQueryable translates queries to remote sources (e.g., SQL).

4. What are the two syntaxes for LINQ?

Answer: Method syntax (e.g., Where(x => x > 5)) and query syntax (e.g., from x in list where x > 5 select x).

5. Explain var in LINQ.

Answer: var infers the query result type (e.g., IEnumerable<T>).

6. What is the purpose of let in LINQ?

Answer: let stores intermediate results in a query (query syntax only).

7. What is the difference between Select and SelectMany?

Answer: Select projects each element; SelectMany flattens sequences (e.g., List<List<int>> to List<int>).

8. Explain GroupBy.

Answer: Groups elements by a key (e.g., group x by x.Category).

9. What is the join clause?

Answer: Combines two sequences based on matching keys (e.g., inner join).

10. What is FirstOrDefault vs. First?

Answer: First throws if empty; FirstOrDefault returns default value.

11. Explain Single vs. SingleOrDefault.

Answer: Single expects exactly one element; SingleOrDefault returns default if empty or throws if multiple.

12. What is Where used for?

Answer: Filters elements based on a condition (e.g., Where(x => x.Age > 18)).

13. Explain OrderBy and ThenBy.

Answer: OrderBy sorts by a key; ThenBy adds secondary sorting.

14. What is the difference between Take and Skip?

Answer: Take(n) returns first n elements; Skip(n) skips first n elements.

15. What is Distinct?

Answer: Returns unique elements (removes duplicates).

16. Explain Concat vs. Union.

Answer: Concat combines sequences (with duplicates); Union combines and removes duplicates.

17. What is Intersect?

Answer: Returns elements present in both sequences (set intersection).

18. What is Except?

Answer: Returns elements in the first sequence not in the second (set difference).

19. Explain Any vs. All.

Answer: Any checks if any element satisfies a condition; All checks if all elements do.

20. What is Count vs. LongCount?

Answer: Count returns int; LongCount returns long for large collections.

21. Explain Sum, Average, Min, Max.

Answer: Aggregate functions for numerical calculations.

22. What is Aggregate?

Answer: Performs a custom aggregation (e.g., sum, product) over a sequence.

23. What is the difference between ToList() and ToArray()?

Answer: ToList() returns a List<T>; ToArray() returns an array. Both force immediate execution.

24. Explain AsEnumerable().

Answer: Converts IQueryable to IEnumerable, switching to in-memory processing.

25. What is AsQueryable()?

Answer: Converts IEnumerable to IQueryable for remote execution.

26. What is Cast?

Answer: Converts elements to a specified type (throws on invalid cast).

27. What is OfType?

Answer: Filters elements by type (ignores invalid casts).

28. Explain DefaultIfEmpty.

Answer: Returns a default value if the sequence is empty.

29. What is Empty?

Answer: Returns an empty IEnumerable<T>.

30. What is Range?

Answer: Generates a sequence of integers (e.g., Enumerable.Range(1, 10)).

31. What is Repeat?

Answer: Generates a sequence with a repeated value (e.g., Enumerable.Repeat("A", 3)).

32. Explain Zip.

Answer: Combines two sequences element-wise (e.g., list1.Zip(list2, (a, b) => a + b)).

33. What is GroupJoin?

Answer: Groups elements from the outer sequence with matching inner elements (like a left join).

34. What is the difference between join and GroupJoin?

Answer: join returns flat results; GroupJoin returns hierarchical results.

35. Explain ToDictionary.

Answer: Converts a sequence to a Dictionary<TKey, TValue>.

36. What is ToLookup?

Answer: Converts a sequence to a Lookup<TKey, TElement> (one-to-many mapping).

37. Explain Reverse.

Answer: Inverts the order of elements.

38. What is SequenceEqual?

Answer: Checks if two sequences are equal (order and elements).

39. What is the difference between TakeWhile and SkipWhile?

Answer: TakeWhile takes elements until a condition fails; SkipWhile skips elements until a condition fails.

40. Explain ElementAt vs. ElementAtOrDefault.

Answer: ElementAt returns the element at an index (throws if out of range); ElementAtOrDefault returns default.

41. What is Last vs. LastOrDefault?

Answer: Last returns the last element (throws if empty); LastOrDefault returns default.

42. Explain Contains.

Answer: Checks if a sequence contains a specific element.

43. What is the difference between Select and SelectMany in terms of performance?

Answer: SelectMany is more efficient for nested collections as it avoids intermediate lists.

44. How does LINQ to SQL work?

Answer: Translates LINQ queries to SQL for database execution.

45. What is PLINQ?

Answer: Parallel LINQ (PLINQ) executes queries across multiple CPUs using AsParallel().

46. Explain AsParallel().

Answer: Enables parallel processing of a LINQ query.

47. What is ForAll in PLINQ?

Answer: Executes an action for each element in parallel (bypasses merging).

48. What is the difference between orderby and group by?

Answer: orderby sorts; group by groups elements by a key.

49. Explain into in LINQ.

Answer: into stores the result of a group or join for further querying.

50. What is DefaultIfEmpty used for in left joins?

Answer: Provides a default value for unmatched elements in a left join (e.g., join ... into g from x in g.DefaultIfEmpty()).


ASP.NET Core MVC Interview Questions (50)

1. What is ASP.NET Core MVC?

Answer: A framework for building web apps using the Model-View-Controller pattern, running on .NET Core.

2. Explain MVC pattern.

Answer: Model (data/logic), View (UI), Controller (handles requests, updates model/view).

3. What is routing?

Answer: Maps URLs to controller actions (e.g., {controller=Home}/{action=Index}/{id?}).

4. What is the purpose of Startup.cs?

Answer: Configures services (ConfigureServices) and middleware pipeline (Configure).

5. Explain middleware.

Answer: Software components that handle requests/responses in a pipeline (e.g., authentication, logging).

6. What is dependency injection (DI) in MVC?

Answer: DI injects dependencies (e.g., services) into controllers, configured in Startup.cs.

7. What is the difference between AddTransient, AddScoped, and AddSingleton?

Answer: Transient: new instance per request; Scoped: instance per HTTP request; Singleton: single instance for all requests.

8. What is a view model?

Answer: A class that passes data from controller to view, shaped for UI needs.

9. Explain ViewBag vs. ViewData.

Answer: ViewData is a dictionary; ViewBag is a dynamic wrapper. Both pass data to views.

10. What is TempData?

Answer: Stores data between redirects (uses session or cookies).

11. What is Razor syntax?

Answer: A markup syntax for embedding C# in HTML (e.g., @Model.Name).

12. Explain partial views.

Answer: Reusable view snippets (e.g., _LoginPartial.cshtml).

13. What is a layout?

Answer: A master template for views (e.g., _Layout.cshtml).

14. What is the @section directive?

Answer: Defines content sections in views that render in layout placeholders.

15. What is tag helpers?

Answer: HTML-like attributes that enhance HTML elements (e.g., <a asp-action="Index">).

16. Explain model binding.

Answer: Maps HTTP request data to action parameters (e.g., form data to a model).

17. What is validation in MVC?

Answer: Uses attributes (e.g., [Required]) and ModelState.IsValid to validate models.

18. What is the ValidateAntiForgeryToken attribute?

Answer: Prevents CSRF attacks by validating tokens in forms.

19. Explain areas.

Answer: Organize large apps into modules (e.g., Admin, Blog).

20. What is the Authorize attribute?

Answer: Restricts access to authenticated users or roles (e.g., [Authorize(Roles="Admin")]).

21. What is the AllowAnonymous attribute?

Answer: Bypasses authentication for specific actions/controllers.

22. Explain filters.

Answer: Logic that runs before/after action execution (e.g., authorization, logging).

23. What are action filters?

Answer: Filters that execute around actions (e.g., OnActionExecuting, OnActionExecuted).

24. What is the IActionFilter interface?

Answer: Defines methods for action filter implementation.

25. Explain exception filters.

Answer: Handle unhandled exceptions (e.g., IExceptionFilter).

26. What is the HandleError attribute?

Answer: Catches exceptions and returns a custom error view.

27. What is the IResultFilter?

Answer: Executes before/after action result execution (e.g., modifying response).

28. What is the IResourceFilter?

Answer: Runs before model binding (e.g., caching).

29. Explain IAsyncActionFilter.

Answer: Async version of action filters for non-blocking operations.

30. What is the difference between ViewResult and PartialViewResult?

Answer: ViewResult renders a full view; PartialViewResult renders a partial view.

31. What is JsonResult?

Answer: Returns JSON-formatted data (e.g., for AJAX).

32. What is FileResult?

Answer: Returns a file (e.g., PDF, image).

33. Explain ContentResult.

Answer: Returns plain text (e.g., return Content("Hello")).

34. What is RedirectResult?

Answer: Redirects to a URL (e.g., return Redirect("https://example.com")).

35. What is RedirectToActionResult?

Answer: Redirects to an action (e.g., return RedirectToAction("Index")).

36. What is the HttpPost attribute?

Answer: Restricts an action to HTTP POST requests.

37. What is the HttpGet attribute?

Answer: Restricts an action to HTTP GET requests.

38. Explain FromForm, FromQuery, FromRoute, FromBody.

Answer: Bind model data from form, query string, route, or request body.

39. What is the ApiController attribute?

Answer: Enables API-specific features (e.g., automatic model validation, problem details).

40. What is the Route attribute?

Answer: Defines custom routes for controllers/actions (e.g., [Route("api/[controller]")]).

41. Explain IActionResult.

Answer: Base type for action results (e.g., ViewResult, JsonResult).

42. What is the View component?

Answer: Reusable UI logic with data (e.g., shopping cart summary).

43. What is the difference between View and PartialView?

Answer: View renders a full page; PartialView renders a snippet.

44. What is the @model directive?

Answer: Declares the model type for a view (e.g., @model IEnumerable<Product>).

45. What is the @using directive?

Answer: Imports namespaces in views (e.g., @using MyProject.Models).

46. What is the @inject directive?

Answer: Injects services into views (e.g., @inject IMyService MyService).

47. Explain IViewLocationExpander.

Answer: Customizes view search paths (e.g., for themes).

48. What is the IViewEngine?

Answer: Locates and renders views (e.g., RazorViewEngine).

49. What is the ITempDataProvider?

Answer: Stores TempData (e.g., in session or cookies).

50. What is the IHostBuilder?

Answer: Configures the app host (e.g., CreateHostBuilder in Program.cs).


WEB API Interview Questions (50)

1. What is ASP.NET Core Web API?

Answer: A framework for building HTTP services that can be consumed by clients (e.g., browsers, mobile apps).

2. What is REST?

Answer: Representational State Transfer (REST) uses HTTP methods (GET, POST, PUT, DELETE) for resource operations.

3. Explain HTTP status codes.

Answer: Codes indicate request outcomes (e.g., 200 OK, 404 Not Found, 500 Internal Server Error).

4. What is the difference between Web API and MVC?

Answer: Web API returns data (JSON/XML); MVC returns views. Web API is stateless; MVC is stateful.

5. What is content negotiation?

Answer: Web API returns data in the format requested by the client (e.g., JSON, XML) via Accept header.

6. What is the ApiController attribute?

Answer: Enables API conventions (e.g., automatic model validation, problem details).

7. Explain IActionResult.

Answer: Base type for action results (e.g., OkResult, NotFoundResult).

8. What is OkResult?

Answer: Returns HTTP 200 OK with optional data.

9. What is CreatedAtActionResult?

Answer: Returns HTTP 201 Created with a location header.

10. What is BadRequestResult?

Answer: Returns HTTP 400 Bad Request.

11. What is NotFoundResult?

Answer: Returns HTTP 404 Not Found.

12. What is NoContentResult?

Answer: Returns HTTP 204 No Content.

13. Explain FromForm, FromQuery, FromRoute, FromBody.

Answer: Bind data from form, query string, route, or request body.

14. What is the [FromBody] attribute?

Answer: Binds data from the request body (e.g., JSON).

15. What is the [FromRoute] attribute?

Answer: Binds data from route parameters.

16. What is the [FromQuery] attribute?

Answer: Binds data from the query string.

17. What is the [FromHeader] attribute?

Answer: Binds data from HTTP headers.

18. Explain model validation.

Answer: Uses attributes (e.g., [Required]) and ModelState.IsValid to validate input.

19. What is the ModelState?

Answer: Contains model state and validation errors.

20. What is the ProblemDetails class?

Answer: Standardized error response format (RFC 7807).

21. What is the ApiController attribute’s role in validation?

Answer: Automatically returns 400 Bad Request if ModelState is invalid.

22. What is dependency injection in Web API?

Answer: Injects services (e.g., repositories) into controllers.

23. What is the IHttpClientFactory?

Answer: Manages HttpClient instances for resilience and performance.

24. Explain middleware in Web API.

Answer: Components in the request pipeline (e.g., authentication, CORS).

25. What is CORS?

Answer: Cross-Origin Resource Sharing (CORS) allows cross-domain requests (configured via middleware).

26. What is the EnableCors attribute?

Answer: Enables CORS for controllers/actions.

27. Explain authentication vs. authorization.

Answer: Authentication verifies identity; authorization grants access.

28. What is JWT?

Answer: JSON Web Token (JWT) is a compact token for secure authentication.

29. What is the Authorize attribute?

Answer: Restricts access to authenticated users/roles.

30. What is the AllowAnonymous attribute?

Answer: Bypasses authentication.

31. What is OpenAPI/Swagger?

Answer: Tools for documenting and testing APIs (e.g., Swashbuckle).

32. What is the ProducesResponseType attribute?

Answer: Documents possible action responses (e.g., [ProducesResponseType(200)]).

33. Explain API versioning.

Answer: Manages API versions (e.g., via URL, query string, header).

34. What is the ApiVersion attribute?

Answer: Specifies API versions for controllers.

35. What is the MapControllers method?

Answer: Maps attribute-routed controllers in Startup.Configure.

36. What is the difference between MapControllerRoute and MapControllers?

Answer: MapControllerRoute defines conventional routes; MapControllers enables attribute routing.

37. What is the IActionFilter in Web API?

Answer: Executes logic before/after actions (e.g., logging).

38. What is the IExceptionFilter?

Answer: Handles unhandled exceptions globally.

39. What is the UseExceptionHandler middleware?

Answer: Catches exceptions globally and returns a custom response.

40. What is the UseStatusCodePages middleware?

Answer: Returns custom responses for status codes (e.g., 404).

41. Explain IAsyncActionFilter.

Answer: Async version of action filters.

42. What is the IResultFilter?

Answer: Executes before/after action results (e.g., modifying response).

43. What is the IResourceFilter?

Answer: Runs before model binding (e.g., caching).

44. What is the UseRouting middleware?

Answer: Matches URLs to endpoints.

45. What is the UseEndpoints middleware?

Answer: Executes matched endpoints.

46. What is the UseHttpsRedirection middleware?

Answer: Redirects HTTP to HTTPS.

47. What is the UseHsts middleware?

Answer: Adds HTTP Strict Transport Security (HSTS) header.

48. What is the UseResponseCaching middleware?

Answer: Enables response caching.

49. What is the ResponseCache attribute?

Answer: Controls caching behavior for actions.

50. What is gRPC?

Answer: A high-performance RPC framework using HTTP/2 (alternative to REST).


JavaScript and React JS Interview Questions (50)

1. What is JavaScript?

Answer: A scripting language for web development, enabling dynamic content and interactivity.

2. Explain var, let, and const.

Answer: var is function-scoped; let and const are block-scoped. const is immutable for primitives.

3. What is hoisting?

Answer: Declarations (e.g., var, functions) are moved to the top of their scope during compilation.

4. What is the difference between == and ===?

Answer: == checks equality with type coercion; === checks strict equality (no coercion).

5. What is a closure?

Answer: A function retains access to its lexical scope, even when executed outside that scope.

6. Explain event delegation.

Answer: Attach a single event listener to a parent element to handle events for child elements (e.g., using event.target).

7. What is the DOM?

Answer: Document Object Model (DOM) represents HTML as a tree structure, manipulated via JavaScript.

8. What is the difference between innerHTML and textContent?

Answer: innerHTML parses HTML; textContent inserts plain text.

9. What is event bubbling?

Answer: Events propagate from the target element up to ancestors.

10. What is event capturing?

Answer: Events propagate from the root down to the target (opposite of bubbling).

11. Explain this in JavaScript.

Answer: this refers to the object executing the current function (context-dependent).

12. What is the difference between call, apply, and bind?

Answer: call/apply invoke a function with a specific this and arguments; bind returns a new function with bound this.

13. What is a promise?

Answer: An object representing eventual completion/failure of an async operation (e.g., fetch).

14. Explain async/await.

Answer: async marks a function as asynchronous; await pauses execution until a promise settles.

15. What is the difference between Promise.all and Promise.race?

Answer: Promise.all waits for all promises to resolve; Promise.race resolves/rejects with the first settled promise.

16. What is a callback?

Answer: A function passed as an argument to another function, executed later (e.g., in async operations).

17. What is the difference between setTimeout and setInterval?

Answer: setTimeout executes once after a delay; setInterval executes repeatedly.

18. Explain the event loop.

Answer: Mechanism that handles callbacks, promises, and timers, executing code in a non-blocking way.

19. What is a higher-order function?

Answer: A function that takes/returns other functions (e.g., map, filter).

20. What is map vs. forEach?

Answer: map returns a new array; forEach returns undefined and mutates the original array.

21. What is filter?

Answer: Returns a new array with elements that pass a test.

22. What is reduce?

Answer: Reduces an array to a single value (e.g., sum, product).

23. What is a pure function?

Answer: A function with no side effects (same input → same output).

24. What is immutability?

Answer: Data cannot be changed after creation (e.g., const for primitives, methods like slice for arrays).

25. What is a module?

Answer: Reusable code units (ES6 modules: import/export).

26. What is the difference between CommonJS and ES modules?

Answer: CommonJS (require) is synchronous; ES modules (import) are asynchronous.

27. What is React?

Answer: A JavaScript library for building user interfaces using components.

28. What is JSX?

Answer: Syntax extension for JavaScript that looks like HTML (compiled to React.createElement).

29. Explain components.

Answer: Reusable UI pieces (functional or class-based).

30. What is props?

Answer: Data passed from parent to child components (immutable).

31. What is state?

Answer: Internal data managed by a component (mutable via setState or useState).

32. What is the difference between state and props?

Answer: Props are passed down; state is internal. Props are immutable; state is mutable.

33. What is a functional component?

Answer: A component defined as a JavaScript function (returns JSX).

34. What is a class component?

Answer: A component defined as an ES6 class (extends React.Component).

35. What is the useState hook?

Answer: Adds state to functional components (e.g., const [count, setCount] = useState(0)).

36. What is the useEffect hook?

Answer: Performs side effects (e.g., data fetching, subscriptions) in functional components.

37. What is the dependency array in useEffect?

Answer: Controls when useEffect runs (e.g., [] runs once; [dep] runs when dep changes).

38. What is the useContext hook?

Answer: Accesses context values without prop drilling.

39. What is the useReducer hook?

Answer: Manages complex state logic (alternative to useState).

40. What is the useRef hook?

Answer: Creates a mutable ref object (e.g., for DOM access or persistent values).

41. What is the useMemo hook?

Answer: Memoizes expensive calculations (recomputes only when dependencies change).

42. What is the useCallback hook?

Answer: Memoizes functions to prevent unnecessary re-renders.

43. What is the component lifecycle?

Answer: Methods in class components (e.g., componentDidMount, componentDidUpdate, componentWillUnmount).

44. What is React Router?

Answer: Library for routing in React apps (e.g., BrowserRouter, Route, Link).

45. What is the difference between controlled and uncontrolled components?

Answer: Controlled components use React state for form data; uncontrolled components use DOM refs.

46. What is the key prop?

Answer: Unique identifier for list items (helps React track changes).

47. What is React Fragments?

Answer: Groups elements without adding extra DOM nodes (e.g., <></>).

48. What is the virtual DOM?

Answer: Lightweight in-memory representation of the real DOM, used for efficient updates.

49. What is reconciliation?

Answer: React’s process of updating the DOM by comparing virtual DOM trees (diffing algorithm).

50. What is Redux?

Answer: A state management library for predictable state updates (actions, reducers, store).

Comments

Popular posts from this blog

Uncontrolled form input in React-JS

  Uncontrolled form input in React-JS? If we want to take input from users without any separate event handling then we can uncontrolled the data binding technique. The uncontrolled input is similar to the traditional HTML form inputs. The DOM itself handles the form data. Here, the HTML elements maintain their own state that will be updated when the input value changes. To write an uncontrolled component, you need to use a ref to get form values from the DOM. In other words, there is no need to write an event handler for every state update. You can use a ref to access the input field value of the form from the DOM. Example of Uncontrolled Form Input:- import React from "react" ; export class Info extends React . Component {     constructor ( props )     {         super ( props );         this . fun = this . fun . bind ( this ); //event method binding         this . input = React . createRef ();...

JSP Page design using Internal CSS

  JSP is used to design the user interface of an application, CSS is used to provide set of properties. Jsp provide proper page template to create user interface of dynamic web application. We can write CSS using three different ways 1)  inline CSS:-   we will write CSS tag under HTML elements <div style="width:200px; height:100px; background-color:green;"></div> 2)  Internal CSS:-  we will write CSS under <style> block. <style type="text/css"> #abc { width:200px;  height:100px;  background-color:green; } </style> <div id="abc"></div> 3) External CSS:-  we will write CSS to create a separate file and link it into HTML Web pages. create a separate file and named it style.css #abc { width:200px;  height:100px;  background-color:green; } go into Jsp page and link style.css <link href="style.css"  type="text/css" rel="stylesheet"   /> <div id="abc"> </div> Exam...

JDBC Database Connectivity using JSP and Servlet, Database connectivity on Java

JDBC Database Connectivity using JSP and Servlet, Database connectivity on Java JDBC:-   JDBC means Java database connectivity, it is used to connect from the front-end(application server) to the back-end(database server) in the case of Java web application. The database provides a set of tables to store records and JDBC will work similarly to the  bridge between the database table and application form. 1)  Class.forName("drivername")  // Manage Drive         Class.formName("com.mysql.jdbc.Driver");  // MYSQL      Class.forName ("oracle.jdbc.driver.OracleDriver"); //Oracle 2)  Manage Connection String     It establish connection from application server to database server, Java provide DriverManage class and getConnection that will return Connection object.    Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/databasename","username","password"); 3)  Manage Statement to...