loading...
Cover image for Cracking The Frontend Interview, Part 5: React

Cracking The Frontend Interview, Part 5: React

hoangbkit profile image Hoang Nguyen Originally published at advancedweb.dev Updated on ・9 min read

React is hugely popular, ecosystem is big, documentation is awesome, and job pool is very competitive already. The interviewers are excited because there are tons of concepts, techniques and libraries to ask about while the interviewing candidates always have the feeling of not good enough.


Cracking the Frontend Interview is an original series on advancedweb.dev, this series acts like my notes and summary on what's really important to tackle a frontend interview.


This post acts like a long introduction about React and its ecosystem, read through it to have a good sense of what involves, follow unfamiliar linked content, and finally dig deep on your own preferred pieces.

Getting Started

React is a JavaScript library for building user interfaces, it has a selling point of running very fast by only updating to real DOM what's necessary based on a diffing algorithm.

Running in a virtual representation makes it possible to become an universal UI library in multiple platforms, all you need to do is implementing different renderers in separate platforms like web, mobile or desktop and you're good to use same syntax and concepts to write truly universal apps.

React core only includes the APIs necessary to define components, renderers manage how a React tree turns into the underlying platform calls — React Dom renders the component tree into respective dom elements, React Native renders the component tree into respective native platform views.

React is not a complete framework like Angular, so it does need external solutions to routing, styling, data fetching, bundling, v.v. You can configure a complete React-based app manually but it requires very steep learning curve, you better use popular React frameworks (Gatsby, Next, Create-React-App, React Native, or Electron) to take advantages of built-in solutions and optimized production build.

React interview questions are expected to be very wide, covering all basic and advanced concepts in React documentation certainly gives you a good start. But React jobs market is getting very competitive, you must dig deeper to go far.

React in a Nutshell

Regardless of your level, mastering all React concepts and APIs is important, managing to remember the definitions of related concepts is the key; failing to explain how something works is okay depends on your current level.

React Official Docs did an excellent job on explaining all the concepts you need to write a React app, all you need to do is going there and read all of them! Following are a few things to keep in mind:

JSX is a syntax extension to JavaScript, similar to a template language, but it has full power of JavaScript, easy to dynamically style or markup depending on current data.

React follow component-based approach which emphasizes the separation of concerns with respect to functionality than global file types. Components are often loosely coupled pieces of code make them easy to reuse and move around. Components receive immutable props from parents and have their own mutable state.

A component has Lifecycle methods executed during the different phases of its life. These methods are available when the component gets created and inserted into the DOM (mounting), when the component updates, and when the component gets unmounted or removed from the DOM.

React favors declarative coding style by mixing up stateful/stateless custom components, primitive DOM elements, web components, not-rendered components (booleans, null, undefined) to build any layouts.

React has two different approaches to dealing with form inputs: an input form element whose value is controlled by React is called a controlled component, an uncontrolled component works like form elements do outside of React.

React favors one-way data binding which results in better code understanding, debugging, deterministic rendering, and time travelling. Normally you'll pass data down the tree and lift shared state up to closest ancestor instead of trying to sync between different components.

You use Context, Hooks, HOCs to deal with cross-cutting concerns like theme, authenticated user, or any truly global data to pass data through component tree without having to pass props down manually at every level.

You use Refs to access DOM nodes or React elements created in the render method in cases of managing focus, text selection, media playback, triggering imperative animations, integrating with third-party DOM libraries. Refs are treated different from normal props, you must use refs forwarding to pass refs down explicitly.

You use Portals to deal with teleported components that exists outside the DOM hierarchy of parent components like modals, tooltips, floating menus or widgets. Teleported component is no longer a child of its parent-components DOM-node but still a child of its parent in the react component tree so react events are still bubbling properly.

React is very sensitive to re-rendering every times something in the tree has changed, optimizing performance by identifying some gotchas that could trigger unintentional renders like always created objects in render() method.

React also has its own development Strict Mode currently helps with identifying components with unsafe lifecycles, warning about legacy string ref API usage, warning about deprecated findDOMNode usage, detecting unexpected side effects, or detecting legacy context API.

How React Works

Knowing how React works under the hood is critical to optimize performance when building complicated apps. It all comes down to only one important point: only re-render what has just changed.

React builds and maintains an internal representation of the rendered UI known as Virtual DOM. It includes the React elements you return from your components. This representation lets React avoid creating DOM nodes and accessing existing ones beyond necessity, as that can be slower than operations on JavaScript objects.

When a component’s props or state change, React decides whether an actual DOM update is necessary by comparing the newly returned element with the previously rendered one. When they are not equal, React will update the DOM.

Internally, React uses several clever techniques to minimize the number of costly DOM operations required to update the UI, this process called reconciliation. The diffing algorithm is heuristic and it has many assumptions, when the assumptions behind them are not met, performance will suffer.

React is unaware of changes made to the DOM outside of React. It determines updates based on its own internal representation, and if the same DOM nodes are manipulated by another library, React gets confused and has no way to recover.

Memoization is the most popular technique to optimize performance in React, especially when dealing with heavy list of items or expensive calculations.

Component Patterns

Components are the primary unit of code reuse in React, writing normal React components is straightforward, but there are cases you need to use special component patterns to handle efficiently.

Before Hooks, Higher Order Components (HOCs) are dominant in terms of handling cross-cutting concerns, they compose the original components by wrapping them in a container component, they are pure functions with zero side-effects. Remember not to use HOCs in render method, you must copy over static methods and and pass through refs manually.

Container Components are part of a strategy of separating responsibility between high-level and low-level concerns. Containers manage things like subscriptions and state, and pass props to components that handle things like rendering UI. HOCs use containers as part of their implementation. You can think of HOCs as parameterized container component definitions.

Hooks allow you to reuse stateful logic without changing your component hierarchy. This makes it easy to share Hooks among many components or with the community. Hooks let you split one component into smaller functions based on what pieces are related (such as setting up a subscription or fetching data)

Hooks are a more direct way to use the React features you already know — such as state, lifecycle, context, and refs. They don’t fundamentally change how React works, and your knowledge of components, props, and top-down data flow is just as relevant.

There are other patterns like Render Props, Proxy Components, or Switch Components. This React Patterns site has the most completed list of component patterns out there, check it out and use what you prefer.

Development Techniques

State management is hard and opinionated, there is no right or wrong, it's just a matter of situation. You can just use React features like component state and context to manage local and global data in simple app; or you can use 3rd-party libraries like redux or mobx when you have reasonable amounts of data changing over time needed to keep as a single source of truth. The golden rule is to keep state as local as possible and lift shared state up the tree.

Data fetching adds another layer of complexity to your application; normally you fetch JSON data from RESTful/GraphQL APIs using HTTP/GraphQL clients (axios, apollo) and put them in local state or global store. It's worth to know error handling, where to put data fetching code, how to test data fetching, pagination, and load more.

In the old days CSS styling is truly global, now we're moving in a direction of component scoped styling; you can use raw CSS, CSS preprocessors, CSS modules, or CSS-in-JS (styled-components), module bundlers will take care of scopes and compiling for you.

Routing in React are often coordinated by libraries (react-router, reach-router) to inject useful features like prefetching or code-splitting.

Whether you love or hate static type checking, you should learn at least Flow or TypeScript because most companies are using them to enforce better code health. It's worth to know compile-time object validators like prop-types or @hapi/joi.

You can test React components similar to testing other JavaScript code. Rendering component trees in a simplified test environment and asserting on their output. Running a complete app in a realistic browser environment (also known as “end-to-end” tests).

In reality, you often use a React framework which is already bundled with many JavaScript tools like linters, transpilers, bundlers, loaders, optimizers, hot-reload servers, css preprocessors, or test runners. Beginners can skip all of those initially and laser focus on React itself, seniors are expected to understand how those JavaScript tools work.

The Bigger Picture

Learning React itself is a must to become a React developer, but don't forget that React is just a part of web development in general, Web fundamentals is a good place to learn all of that.

The component-based approach of React and other frontend frameworks like Vue and Angular has changed the way our web looks like today. Take a quick look at Vue and Angular to have a sense of pros and cons between them.

React is involved in many React frameworks which serve different needs like Create-React-App for client-side rendering, Next.js for server-side rendering, Gatsby for static sites, React Native for universal mobile apps, Electron for desktop apps. Which one you're using? Be prepared to be asked about that too!

Don't forget that each of above React frameworks has its own concepts and techniques separated from React itself, a quick tip is to focus on universal learning path to easily switch between them.

Where to Go From Here?

You've just finished reading a long introduction to React and its moving parts which are every important in interviews, don't feel overwhelmed by encountering so many unfamiliar buzzwords, the fasted way to fill the gap is to build a useful product while using as many React concepts as possible.

Developers tend to be very biased on what they know best, so keep an open mind while learning, give available options a try and pick what works for you.

Reread this post multiple times to familiarize all keywords, keep digging deep on unfamiliar ones by searching Google or reading following excellent resources:

React Resources — This site curates all kind of resources related to React and categorized very thoroughly

Kent C. Dodds Blog — Kent is maintaining one of the best blogs about React, JavaScript and testing.

Overreacted.io — A personal blog by famous Dan Abramov, a good place to learn how React works under the hood.

React Interview Questions & Answers — A github repo with more than 300 questions and answers about React and its ecosystem.

Top 70 React Interview Questions and Answers — A good post from guru99, the answers are quite short and unclear, anyway it's good to revise your knowledge.

Discussion

pic
Editor guide