Job interview Flashcards
prepare for js interview
Create a ‘Like’ button with the following UI design and states - https://i.imgur.com/4JLyipM.png
Requirements
x - The button should show the text ‘Like’ and an icon to the left of the text.
x- The button should have gray text, icon and border.
x- When the user hovers over the button, the text, icon and border should turn red.
x- When the user clicks the button its state should toggle, the text and icon should turn white and the background colour should become red.
x- When the button is mounted it should call an API endpoint get the initial state (enabled or disabled).
- Clicking the button should call an API endpoint to update the new state (enabled or disabled).
- While the request is processing, the button should show a loading state.
*/—
import React, { useState, useEffect } from 'react'; import styles from './Button.module.css'; // Import CSS using CSS Modules const ButtonComponent = () => { const [isActive, setIsActive] = useState(false); const [isLoading, setIsLoading] = useState(false); const fetchData = async (url, method, body = null) => { setIsLoading(true); try { const response = await fetch(url, { method, headers: { 'Content-Type': 'application/json' }, body: body ? JSON.stringify(body) : null, }); if (!response.ok) { throw new Error(`Failed to ${method} data`); } const data = await response.json(); return method === 'GET' ? data.isActive : null; // Assuming 'isActive' property } catch (error) { console.error(`Error ${method}ing data:`, error); } finally { setIsLoading(false); } }; useEffect(() => { fetchData('your-api-endpoint', 'GET') .then(data => setIsActive(data)) // Set initial state .catch(error => console.error(error)); }, []); const toggleActive = async () => { const updatedActive = !isActive; await fetchData('your-api-endpoint', 'POST', { isActive: updatedActive }); setIsActive(updatedActive); }; return ( <button className={`${styles.button} ${isActive ? styles.active : styles.inactive}`} disabled={isLoading} onClick={toggleActive} > {/* ... rest of the component JSX ... */} </button> ); }; export default ButtonComponent;
What are keys in react?
A “key” is a special string attribute you need to include when creating lists of elements in React. Keys are used in React to identify which items in the list are changed, updated, or deleted.
Keys are used to give an identity to the elements in the lists. It is recommended to use a string as a key that uniquely identifies the items in the list.
Disadvantages of real DOM :
Every time the DOM gets updated, the updated element and its children have to be rendered again to update the UI of our page. For this, each time there is a component update, the DOM needs to be updated and the UI components have to be re-rendered.
Example:
React JS Refs
Refs are a function provided by React to access the DOM element and the React elements created in components. They are used in cases where we want to change the value of a child component, without making use of props and state.
How does virtual DOM actually make things faster?
When anything new is added to the application, a virtual DOM is created and it is represented as a tree. Each element in the application is a node in this tree. So, whenever there is a change in the state of any element, a new Virtual DOM tree is created. This new Virtual DOM tree is then compared with the previous Virtual DOM tree and make a note of the changes. After this, it finds the best possible ways to make these changes to the real DOM. Now only the updated elements will get rendered on the page again.
Controled components
Controlled Components
In simple HTML elements like input tags, the value of the input field is changed whenever the user type. But, In React, whatever the value the user types we save it in state and pass the same value to the input tag as its value, so here DOM does not change its value, it is controlled by react state. These are known as Controlled Components.
What are react hooks?
Hooks are reusable functions that provide access to state in React Applications. Hooks give access to states for functional components while creating a React application. It allows you to use state and other React features without writing a class
Use Context ?
Usually, you will pass information from a parent component to a child component via props. But passing props can become verbose and inconvenient if you have to pass them through many components in the middle, or if many components in your app need the same information. Context lets the parent component make some information available to any component in the tree below it—no matter how deep—without passing it explicitly through props.
global data -> current authenticated user or theme(e.g. color, paddings, margins, font-sizes).
The Context API allows for more flexibility in how state is managed and accessed compared to Redux, which follows a more structured pattern with actions, reducers, and a single store.
Context lets a component provide some information to the entire tree below it.
To pass context:
Create and export it with export const MyContext = createContext(defaultValue).
Pass it to the useContext(MyContext) Hook to read it in any child component, no matter how deep.
Wrap children into <MyContext.Provider value={…}> to provide it from a parent.
Context passes through any components in the middle.
Context lets you write components that “adapt to their surroundings”.
Before you use context, try passing props or passing JSX as children.
useState Hook
The useState Hook provides those two things:
A state variable to retain the data between renders.
A state setter function to update the variable and trigger React to render the component again.
When you call useState, you are telling React that you want this component to remember something:
const [index, setIndex] = useState(0);
In this case, you want React to remember index.
The convention is to name this pair like const [something, setSomething].
The only argument to useState is the initial value of your state variable
Every time your component renders, useState gives you an array containing two values:
The state variable (index) with the value you stored.
The state setter function (setIndex) which can update the state variable and trigger React to render the component again.
What is useEffect hook in React?
Some components need to stay connected to the network, some browser API, or a third-party library, while they are displayed on the page. These systems aren’t controlled by React, so they are called external.
To connect your component to some external system, call useEffect at the top level of your component:
The useEffect in ReactJS is used to handle the side effects such as fetching data and updating DOM. This hook runs on every render but there is also a way of using a dependency array using which we can control the effect of rendering
So run on update of var in the dependancy [test]
Once when dependacy is []
and on every render wheren there is no dependacy array so if you set state in useEffect and dont have dependancy array you have an infinite loop
How does it useEffect work?
You call useEffect with a callback function that contains the side effect logic.
By default, this function runs after every render of the component.
You can optionally provide a dependency array as the second argument.
The effect will only run again if any of the values in the dependency array change.
Controlling side effects in useEffect :
1. To run useEffect on every render do not pass any dependency
useEffect(()->{
// Example Code
})
- To run useEffect only once on the first render pass any empty array in the dependecy
useEffect(()->{
// Example Code
}, [] )
- To run useEffect on change of a particular value. Pass the state and props in the dependency array
Syntax Parser, Execution Context, and Lexical Environment
Syntax parser - a program that reads your code and determines what it does and if its grammar/syntax is valid.
When you write JavaScript it isn’t directly telling computer what to do. You’re writing code, but then someone else built programs that convert your JS into something that computer can understand. Those programs are called compilers or interpreters.
Compilers go character by character and translate your code into a set of instructions. Important to understand is that during that process programmers who wrote that compiler can choose to do extra stuff. Your code is not what actually is given to a computer but a translation of it.
Lexical environment - where something sits physically in the code you write and what surrounds it. In JavaScript where you write something is important.
Execution context - a wrapper to help manage the code that is running. There are lots of lexical environments, areas of the code that you look at physically, but which one is currently running is managed via execution contexts. Execution context contains your running code, but it can also contain things beyond what you’ve written in your code. Because remember that your code is being translated by a syntax parser.
The Scope Chain
If JavaScript engine doesn’t find variable in it’s own environment it looks in the outer environment. That whole process of searching of variable in outer lexical environments down the chain is called the scope chain.
Hoisting
Hoisting - because of the way JS works, you can write in your code a call to a function before an actual function and it will execute without any errors.
b();
function b() {
console.log(‘This works!’);
}
let avoids Hoisting
Asynchronous Callbacks
Asynchronous - executed more than one at a time. What is happening inside JS engine is synchronous. Its just the browser is putting things asynchronously in the event queue.
Event queue - events like click and others are placed in the queue. And this queue starts to get processed in the order it happened only when execution stack is empty.
Conceptual Aside Coercion
Coercion - converting a value from one type to another. This happens quite often in JavaScript because it’s dynamically typed. For example adding a number to a string would result in number being converted to a string:
7 + ‘7’// would be = ‘77’
Immediately Invoked Functions Expressions (IIFEs)
Using an Immediately Invoked Function Expression (IIFE):
var firstname = ‘John’;
(function(name) {
var greeting = 'Inside IIFE: Hello'; console.log(greeting + ' ' + name);
}(firstname)); // IIFE
Framework Aside IIFEs and Safe Code
IIFE creates a new execution context so it’s safe code because it is wrapped in separate execution context and prevents variable names collision. Wrapping code libraries is very common pattern to not clash code with the global object. You can reference to global object by passing window as a parameter.
Understanding Closures
When a function runs and completes it is removed from execution stack, but variables created and saved in that execution phase are still stored in memory and can be accessed from down the scope.
~~~
function greet(whattosay) {
return function(name) {
console.log(whattosay + ‘ ‘ + name;
}
}
var sayHi = greet(‘Hi’);
sayHi(‘Jason’);
~~~
Inside the variable sayHi we run greet function which returns another function and passes string ‘Hi’. After that functions is finished and it is popped from the execution stack. But whattosay variable still sits saved in the memory with a value Hi. So when we call function sayHi it will go in the outer environment and look for whattosay variable and will find it and log “Hi Jason”. We describe this proccess as execution context has closed in outer variables.
Closures And Callbacks
Callback function - a function you give to another function to be run when the other function is finished.