Collection of Modern React Frontend interview questions
Tags: react, career, interview
Published: 2020-03-31 07:34:51

Recently, I have been thinking that I want to find a new Frontend (React) job. And after some interviews, I highlighted the main questions and my answers, and make a short note for myself.

This article it is a collection of interesting React interview questions.


<h3>1 — What data types have in JavaScript?</h3>

Let's start with the primitives:

<ul>
    <li><strong>String</strong> — any text values.</li>
    <li><strong>Boolean</strong> — Boolean type, takes two possible meanings, sometimes called true or false.</li>
    <li><strong>Number/Float</strong> — Responsible for the numeric type, and Float for non-numeric, it is worth noting Float and Number in JS by viewing through <code>typeof</code>, this is the same type.</li>
    <li><strong>NaN</strong> — property is a value representing Not-A-Number.</li>
    <li><strong>Undefined</strong> - we can get it when we try to get an undefined variable.</li>
    <li><strong>BigInt</strong> — because Number have limitation in his value, for work with big numbers values number will come to the rescue BigInt, maximum value may be getting with call <code>Number.MAX_SAFE_INTEGER.</code></li>
    <li><strong>Symbol</strong> — (Added in ES6) allows create value instance whom will be unique and unchangeable. May be used in example upon realization Dependency Injection, for premises dependencies unique identification, instead of interfaces like in Java/C#.</li>
</ul>

It is also worth continuing:

<ul>
    <li><strong>Null</strong> — tells us that the variable is defined, but does not have. By specification is it object(<code>typeof</code>).</li>
    <li><strong>Object</strong> — simple data structure that can have its own properties and methods. Based on it created another data types such as: <em>Map, Set, WeakMap, WeakSet.</em></li>
    <li><strong>Array</strong> — which are high-level, list-like objects.</li>
    <li><strong>Function</strong> — serves to determine the functions.</li>
</ul>

Also useful to note:

<ul>
    <li><strong>Proxy</strong> — «turns around» other object and may intercept (and, if desired, process it yourself) different actions with him, for example get/set property and other.</li>
</ul>

And also types <em>Map, Set, WeakMap, WeakSet</em>.

<h3>2 — What is Http?</h3>

Http it is a one of the protocols that the browser uses to communicate with server. If view him lifecycle, then when entering on page by domain YouTube.com browser make request to server, but to server access can receive only by his IP-address, for example <em>49.12.15.17</em>. And so they come to DNS servers that store information about the domain whose IP address is assigned, and it is also worth noting that, according to the standard, Http uses the 80th port for the request.

And after browser received a content page, he start to parse HTML/CSS/JS via using blink and V8 engine.

But if you go deeper, then the Http protocol has versions, for example Http 1.1, which are widespread (not statistics, personal opinion of the author). There is also a version of Http 2, which in turn differs from version 1.1 in its improved support for parallel loading of static resources(Multiplexing multiple requests in a single TCP connection). And at the moment there Http 3, it in turn implements UDP-based multiplexing.

<h3>3 — Difference between useState and useRef?</h3>

Is useState and useRef hooks we may to store our information between re-renders. But main difference it is what react component after change state in useState will re-render, whire useRef not. 

For example with useRef we may to realize useUpdate hook. what would work only when component update, not on first render.

```javascript
const useUpdate = (fn, deps = []) => {
    const isMount = useRef(true)

    return useEffect(() => {
        if (isMount.current) {
            isMount.current = false
        } else {
            fn()
        }
    }, [isMount, ...deps])
}
```

<h3>4 — How to work Event Loop under hood?</h3>

JavaScript in the browser runs in single-threaded mode, which has own «Life cycle». For example if we call:

```javascript
setTimeout(() => calledSecond(), 1000)

calledFirst()
```

There we wand call a some function after 1000 milliseconds. When the code executing the JavaScript engine arrives at this line and passes our function to Call Stack, and goes continue executing another code, but when 1000 milliseconds will pass and Event Loop checks Call Stack again, it will see that this function is ready, and execute it.

But then he will meet heavy synchronous operation, he will stay and wait until operation will be done. And it this moment Event Loop will be blocked, and dont execute code further, that is Event Loop dont get to use guarantee what we will call function in setTimeout after 1000 milliseconds, he will call it when next time when Event Loop start to check Call Stack on other iteration and will see that function is ready. More details here.

<h3>5 — What is Iterable?</h3>

JavaScript have so called iterable objects, that is objects content of that we may can sort out. Like for example an array. Enumeration itself, for the most part, is carried out using iterators (for example, the for..of construct uses iterators to enumerate elements). In object we can to define a key Symbol.iterator and in this function should be return object with called next function.

<h3>6 — What is generator?</h3>

It is a function what can to stop and continue function execution, and return intermediate result and further continue executing in arbitrary moment.

```javascript
function* generatorFn() {
    yield someFunction()
}
```

Commonly used as a replacement async/await to work with asynchronous operations. For example Redux-Saga library.

<h3>7 — What are the ways in React to pass data from parent component?</h3>

In React we may to use just a props drilling or Context API.

```javascript
const CounterContext = createContext({
    counter: 0,
    handleIncrement: () => {},
})

const useCounter = () => useContext(CounterContext)

const Wrapper = ({ children }) => {
    const [counter, setCounter] = useState(0)

    const handleIncrement = useCallback(() => setCounter(counter + 1),
        [counter])

    /* or */

    const handleIncrement = useCallback(() => setCounter(counter =>
        counter + 1), [])

    return (
        <CounterContext.Provider
            value={{
                counter,
                handleIncrement,
            }}       
        >
            {children}
        </CounterContext.Provider>
    )
}

const Counter = () => {
    const { counter, handleIncrement } = useCounter()

    return (
        <>
            <p>Count: {counter}</p>
            <button onClick={handleIncrement}>+1</button>
        </>
    )
}

const App = () => (
    <Wrapper>
        <Counter />
    </Wrapper>
)
```

But if our component with data have access to just children from props we may to use React.cloneElement(children, customProps) or we may to use children(customProps) and to parent component we need to pass child component like a function, just like with using LocationContext.Consumer (Render Callback).

```javascript
const Wrapper = ({ children }) => {
    const [counter, setCounter] = useState(0)

    const handleIncrement = useCallback(() => setCounter(counter + 1),
        [counter])

    return (
        <>
            {children({
                counter,
                handleIncrement,
            })}
            {/* or */}
            {React.cloneElement(
                children,
                {
                    counter,
                    handleIncrement,
                },
            )}
        </>
    )
}

const Counter = ({ counter, handleIncrement }) => (
    <>
        <p>Count: {counter}</p>
        <button onClick={handleIncrement}>+1</button>
    </>
)

const App = () => (
    <Wrapper>
        {props => <Counter {...props} />}
        {/* or */}
        <Counter />
    </Wrapper>
)

```

<h3>8 — When we want to listen a window scroll event, how we may to optimize this?</h3>

We may to addEventListener wrap around debounce or throttling function, it is minimize function calls.

Or we can use <em>IntersectionObserver API</em>, when we need to detect what we have in View targetElement. <em>IntersectionObserver API</em> have polyfills, we dont need to worry about cross-browser support.

<h3>9 — What are the ways to optimize animations?</h3>

In JavaScript we may to methods like <em>requestAnimationFrame/requestIdleCallback</em>. 

For CSS we may to use property like <em>will-change</em>, what say to browser that property will changed in future. And if we animate we need to use GPU optimized properties like <em>transform</em>, and dont use <em>position</em> when we animate element position.