My REACT Set
What's the difference between cookie and localStorage?
-cookies store very small amounts of data (4k bytes), set expiration date -localstorage can store more data (2.5-5MBs depending on browser) and doesn't expire when the user ends the session. Storage objects work much like regular JavaScript objects: simply set a property of the object to a string, and the browser will store that string for you. -localStorage = persistant and scoped to the domain. -Cookies = the old school way of doing all of the above. Stores name/value pairs per domain.
When do you use HOC?
1. Code reuse, logic and bootstrap abstraction 2. Render High jacking 3. State abstraction and manipulation 4. Props manipulation
What are the limitations of ReactJS?
1. React is just a view library, not a full-blown framework 2. There is a learning curve for beginners who are new to web development. 3. Integrating React.js into a traditional MVC framework requires some additional configuration 4. The code complexity increases with inline templating and JSX. 5. Too many smaller components leading to over-engineering or boilerplate
How would you write an inline style in React?
<div style={{ height: 10 }}>
What is the purpose of using super constructor with props argument?
A child class constructor cannot make use of this reference until super() method has been called. The same applies for ES6 sub-classes as well. The main reason of passing props parameter to super() call is to access this.props in your child constructors.
What are Higher-Order components?
A higher-order component (HOC) is a function that takes a component and returns a new component. We call them as "pure' components" because they can accept any dynamically provided child component but they won't modify or copy any behavior from their input components. const EnhancedComponent = higherOrderComponent(WrappedComponent);
When does componentDidUpdate run?
After a dom update. ie. the component updates or re-renders, so basically when state or prop changes. Render runs first before componentDidUpdate runs. You typically do things in it like make a request to an API, create event listeners, create subscriptions
When does componentDidMount run?
After the first render, when the component is first mounted on the DOM. Think of it like initialize app
Why did you decided to work with React?
All frameworks are tools. And each has its own pros and cons. What I decided to use is based more on the project. I chose React because there are more job opportunities out there. I also love Javascript and I believe using React teaches me better Javascript principles.
How would React Hooks change the way React is written?
Allow you to create every component as a functional component
What is the difference between Vue vs React vs Angular?
Angular has a specific way of doing things. It's good for a large team of developers because it ensures everyone sticks to the same rule and tool. Angular uses two-way data binding. Based on MVC (Model-View-Controller) architecture React allows you to be more flexible with your code. React goes for single-data flow. Based on Virtual Dom. Vue is simple and easy to pick up. Vue supports both two-way and single-data. Based on virtual dom.
What do fragments do?
Fragments let you return a list of children without adding extra nodes to the DOM.
What is Hot Module Replacement?
Hot Module Replacement (HMR) exchanges, adds, or removes modules while an application is running, without a full reload. This can significantly speed up development in a few ways: Retain application state which is lost during a full reload. Save valuable development time by only updating what's changed. Modifications made to CSS/JS in the source code results in an instant browser update which is almost comparable to changing styles directly in the browser's dev tools.
What are stateful components?
If the behaviour of a component is dependent on the state of the component then it can be termed as stateful component. These Stateful components are always class components and have a state that gets initialized in the constructor. class App extends Component { this.state = { count: 0 }; } render() { } }
When to use a Class Component over a Functional Component?
If the component need state or lifecycle methods then use class component otherwise use functional component.
Describe how events are handled in React.
In order to solve cross browser compatibility issues, your event handlers in React will be passed instances of SyntheticEvent, which is React's cross-browser wrapper around the browser's native event. These synthetic events have the same interface as native events you're used to, except they work identically across all browsers. What's mildly interesting is that React doesn't actually attach events to the child nodes themselves. React will listen to all events at the top level using a single event listener. This is good for performance and it also means that React doesn't need to worry about keeping track of event listeners when updating the DOM.
Where does the Provider component do?
It's where data is going to live. It's similar to the Redux store.
What is JEST?
Jest is a JavaScript unit testing framework made by Facebook based on Jasmine and provides automated mock creation and a jsdom environment. It's often used for testing React components.
What is the difference between a Presentational component and a Container component?
Presentational components are concerned with how things look. They generally receive data and callbacks exclusively via props. These components rarely have their own state, but when they do it generally concerns UI state, as opposed to data state. Container components are more concerned with how things work. These components provide the data and behavior to presentational or other container components. They call Flux actions and provide these as callbacks to the presentational components. They are also often stateful as they serve as data sources.
How would you prevent a component from rendering in React?
Return null from the render method.
What's the difference between an "Element" and a "Component" in React?
Simply put, a React element describes what you want to see on the screen. Not so simply put, a React element is an object representation of some UI. A React component is a function or a class which optionally accepts input and returns a React element (typically via JSX which gets transpiled to a createElement invocation).
What is state in ReactJS?
State of a component is an object that holds some information that may change over the lifetime of the component. We should always try to make our state as simple as possible and minimize the number of stateful components.
What are the arguments for useEffect?
The first one is a call back function, the second is an array of values that if changed, would activate useEffect beyond the initial run. If you only want to run an effect when mounting (ie. componentDidMount), then you pass in an empty array for the second argument.
What are stateless components?
There is no state being stored by this component. If the behavior is independent of its state then it can be a stateless component. You can use either a function or a class for creating stateless components. Unless you need to use lifecycle hook in your components, you should go for stateless functional components. There are a lot of benefits if you decide to use stateless functional components here; they are easy to write, understand, and test, and you can avoid the this keyword altogether.
What is Flux?
Unidrectional application flow paradigm popular a few years back in React; mostly superceded by Redux these days.
How do you prevent the default behavior in an event callback in React?
You call e.preventDefault(); on the event e passed into the callback.
What is inline conditional expressions?
You can use either if statements or ternary expressions which are available from JS to conditionally render expressions. Apart from these approaches, you can also embed any expressions in JSX by wrapping them in curly braces and then followed by JS logical operator(&&). <h1>Hello!</h1> {messages.length > 0 && <h2> You have {messages.length} unread messages. </h2>
What's the difference between a controlled component and an uncontrolled one in React?
A controlled component has its state completely driven by React, Uncontrolled components can maintain their own internal state. E.g., a textarea's value.
What does this line mean visible && <Checkbox />
If visible is true, Javascript will evaluate the right side and render Checkbox. If visible is false, JS will not evaluate the right side and checkbox won't be rendered.
What does it mean for a component to be mounted in React?
It has a corresponding element created in the DOM and is connected to that.
Why is it necessary to capitalize the components?
It is necessary because components are not the DOM element but they are constructors. If they are not capitalized, they can cause various issues and can confuse developers with several elements.
What is the use of refs?
The ref is used to return a reference to the element. They can be useful when we need direct access to DOM element or an instance of a component. Refs allow you to get direct access to a DOM element or an instance of a component. It's often misunderstood that you need to use a class component in order to use refs, but refs can also be used with functional components by leveraging closures in JavaScript.
How do lifecycle methods correspond to Hooks?
-constructor: Function components don't need a constructor. You can initialize the state in the useState call. -getDerivedStateFromProps: Schedule an update while rendering instead. -render: This is the function component body itself. -componentDidMount, componentDidUpdate, componentWillUnmount: The useEffect Hook can express all combinations of these (including less common cases). -componentDidCatch and getDerivedStateFromError: There are no Hook equivalents for these methods yet, but they will be added soon.
What are the advantages of React?
1. Increases the application's performance with Virtual DOM. Due to its diffing algorithm, it only manipulates the DOM as much as it needs to. It only updates the necessary nodes 2. JSX makes code easier to read and write 3. You can render React on the server-side. This enables improves SEO and performance. It is easy to test. 4. Easy to integrate with other frameworks (Angular, BackboneJS) since it is only a view library 5. Easy to write UI Test cases and integration with tools such as JEST. 6. It is easy to know how a component is rendered, you just need to look at the render function.
How do we pass a property from a parent component props to a child component?
<ChildComponent someProp={props.someProperty} />
What are controlled components?
A ReactJS component that controls the input elements within the forms on subsequent user input is called "Controlled component". i.e, every state mutation will have an associated handler function. For example, to write all the names in uppercase letters, we use handleChange as below, handleChange(event) { this.setState({ value: event.target.value.toUpperCase() }); }
What is a component?
A component is a container of one or more visual elements that form parts of the DOM, parter of the user interface that users see on the browser. State is basically component data
What is the difference between Element and Component?
An element is a plain object describing what you want to appear on the screen in terms of the DOM nodes or other components. Elements can contain other elements in their props. Creating a React element is cheap. Once an element is created, it is never mutated. Whereas a component can be declared in several different ways. It can be a class with a render() method. Alternatively, in simple cases, it can be defined as a function. In either case, it takes props as an input, and returns an element tree as the output. JSX transpiled as createElement at the end.
What is the point of Redux?
Application state management that is easy to reason about, maintain and manage in an asynchronous web application environment.
What happens during the lifecycle of a React component?
At the highest level, React components have lifecycle events that fall into three general categories: 1. Initialization 2. State/Property Updates 3. Destruction
What is the point of clean up in React?
Because you might add more and more effect everytime the component re-renders, eg. event listeners. This is awful for performance.
What is the difference between state and props?
Both props and state are plain JavaScript objects. While both of them hold information that influences the output of render, they are different in their functionality with respect to component. -Props get passed to the component similar to function parameters. They are received from above and immutable as far as the Component receiving them is concerned. A Component cannot change its props, but it is responsible for putting together the props of its child Components. -State is managed within the component similar to variables declared within a function. It is mutable. The state is a data structure that starts with a default value when a Component mounts. It may be mutated across time, mostly as a result of user events.
What are the differences between a class component and functional component?
Class components allows you to use additional features such as local state and lifecycle hooks or having functions inside them. Also, they enable your component to have direct access to your store and thus holds state. When your component just receives props and renders them to the page, this is a stateless functional component, for which a pure function can be used. These are also called dumb components or presentational components.
What is the difference between component and container in react Redux?
Component is part of the React API. A Component is a class or function that describes part of a React UI. Container is an informal term for a React component that is connected to a redux store. Containers receive Redux state updates and dispatch actions, and they usually don't render DOM elements; they delegate rendering to presentational child components.
What is context?
Context provides a way to pass data through the component tree without having to pass props down manually at every level. For example, authenticated user, locale preference, UI theme need to be accessed in the application by many components. Instead of having to use redux, you can just use context. const {Provider, Consumer} = React.createContext(defaultValue);
What is Flow?
Flow is a static type checker, designed to find type errors in JavaScript programs, created by Facebook. Flow types can express much more fine-grained distinctions than traditional type systems. For example, Flow helps you catch errors involving null, unlike most type systems.
How is React different from AngularJS (1.x)?
For example, AngularJS (1.x) approaches building an application by extending HTML markup and injecting various constructs (e.g. Directives, Controllers, Services) at runtime. As a result, AngularJS is very opinionated about the greater architecture of your application — these abstractions are certainly useful in some cases, but they come at the cost of flexibility. One can say that Angular is more strict By contrast, React focuses exclusively on the creation of components, and has few (if any) opinions about an application's architecture. This allows a developer an incredible amount of flexibility in choosing the architecture they deem "best" — though it also places the responsibility of choosing (or building) those parts on the developer.
Explain why and how to use HOC?
HoC is a function that accepts a component as argument and returns a new Component that renders the passed in one. This new Component is enhanced with an additional functionality. const HoC = BaseComponent => EnhancedComponent
What's the benefit of using react hooks?
Hooks apply the React philosophy (explicit data flow and composition) inside a component, rather than just between the components. Unlike patterns like render props or higher-order components, Hooks don't introduce unnecessary nesting into your component tree. Hooks are a way for function components to "hook" into React functionality. Previously, when you wanted React components to have state or side effects, you needed to extend the base React Component class. Now, function components need only to apply a hook to gain this functionality. Hooks offer a new way to reuse functionality between components. Hooks let you always use functions instead of having to constantly switch between functions, classes, higher-order components, and render props. Hooks could reduce your bundle size because code using Hooks tends to minify better than equivalent code using classes Hooks let you use React features (like state) from a function — by doing a single function call No more class, this, binding, lifecycles
What is boilerplate in React?
In programming, the term boilerplate code refers to blocks of code used over and over again. Let's assume your development stack consists of several libraries, such as React, Babel, Express, Jest, Webpack, etc. ... A boilerplate is a template that you can clone and reuse for every project.
Where is the state kept in a React + Redux application?
In the store.
What does arrow function do in React?
It automatically binds 'this', allowing you to write function expression within class components. Arrow functions don't redefine the value of this within their function body. This makes it a lot easier to predict their behavior when passed as callbacks, and prevents bugs caused by use of this within callbacks. Clearer syntax
What does useState do?
It creates a hook for setting state in a functional component. For example, const [guessAttempts, setGuessAttempts] = useState([0]) guessAttempts is the state value, setGuessAttempts is the function that will change the value of guessAttempts, useState([0]) sets the initial value of guessAttempts to be [0]. If you want guessAttempts to be nothing, then write useState([ ])
What does useEffect do?
It gets executed every time something renders. It runs after every render. It behaves similarly to componentDidMount, componentDidUpdate, and componnentWillUnmount. The callback function that gets passed into useEffect is called effect. Like useState, we can have more than one useEffect for each component. If you return a function within useEffect, that function will get called before the useEffect runs again, effectively acting like componentDidUpdate. If the component gets remove, then it acts like componentWillUnmount
What are the advantages of using React?
It is easy to know how a component is rendered, you just need to look at the render function. JSX makes it easy to read the code of your components. It is also really easy to see the layout, or how components are plugged/combined with each other. You can render React on the server-side. This enables improves SEO and performance. It is easy to test. You can use React with any framework (Backbone.js, Angular.js) as it is only a view layer.
When does componentWillUnmount run?
It is invoked right before a component is removed from the DOM, right before it disappears from the view. The initial subscriptions or event listeners from componentDidMount are torn down. It's meant to reverse things that were set up in componentDidMount. CDM sets everything up and CU puts an end to things. Thus, you don't change state here
What are the major features of ReactJS?
It uses VirtualDOM instead RealDOM because RealDOM manipulations are expensive. Supports server-side rendering Follows Unidirectional data flow or data binding Uses reusable UI components to develop the view
What is JSX?
JSX is JavaScript with extensions. Useful for creating React elements with the full power of JavaScript. Not required for a React app, but typically it's used. It's syntax notation for JavaScript XML(XML-like syntax extension to ECMAScript). It stands for JavaScript XML. It provides expressiveness of JavaScript along with HTML like template syntax. For example, the below text inside h1 tag return as javascript function to the render function,
When rendering a list what is a key and what is its purpose?
Keys help React identify which items have changed, are added, or are removed. Keys should be given to the elements inside the array to give the elements a stable identity. The best way to pick a key is to use a string that uniquely identifies a list item among its siblings. render () { return ( <ul> {this.state.todoItems.map(({task, uid}) => { return <li key={uid}>{task}</li> })} </ul> ) } Most often you would use IDs from your data as keys. When you don't have stable IDs for rendered items, you may use the item index as a key as a last resort. It is not recommend to use indexes for keys if the items can reorder, as that would be slow.
What are portals in ReactJS?
Portal is a recommended way to render children into a DOM node that exists outside the DOM hierarchy of the parent component. ReactDOM.createPortal(child, container); The first argument (child) is any renderable React child, such as an element, string, or fragment. The second argument (container) is a DOM element.
What are props in React?
Props are data passed down from a parent component to a child component. Props are stored as properties on that object. Props do not have to just be data - callback functions may be passed in as props. The primary purpose of props is to provide following component functionality: 1. Pass custom data to your React component. 2. Trigger state changes.
How does React work?
React creates a virtual DOM. When state changes in a component it first runs a "diffing" algorithm, which identifies what has changed in the virtual DOM. Then it goes through reconciliation, where it updates the DOM with the results of diff.
What is React hooks?
React hooks are functions that grant access to React features or tools in a functional component. Released in v16.8.0, it represents the future of React. Hooks let you use state and other React features without writing a class so every component is a functional component. You can't use Hooks inside of a class component. Hooks let us organize the logic inside a component into reusable isolated units. With Hooks, you can - Use state within a functional React component. - Make shared behaviors across different components into a hook, that you previously could not really refactor into shared code. - Use hooks instead in place of render props and higher-order components
What is React?
React is an open-source JavaScript library created by Facebook for building UIs in web and mobile applications. React's core purpose is to build UI components; it is often referred to as just the "V" (View) in an "MVC" architecture. It is used for handling view layer for web and mobile apps. React was created by Jordan Walke, a software engineer working for Facebook. ReactJS was first deployed on Facebook's newsfeed in 2011 and on Instagram.com in 2012.
What is the difference between React Native and React?
ReactJS is a JavaScript library, supporting both front end web and being run on the server, for building user interfaces and web applications. React Native is a mobile framework that compiles to native app components, allowing you to build native mobile applications (iOS, Android, and Windows) in JavaScript that allows you to use ReactJS to build your components, and implements ReactJS under the hood.
How to create refs?
Refs are created using React.createRef() method and attached to React elements via the ref attribute. In order to use refs throughout the component, just assign the ref to the instance property with in constructor. myRef = React.createRef(); } render() { return <div ref={this.myRef} />; }
What is the purpose of callback function as an argument of setState?
The callback function is invoked when setState finished and the component gets rendered. Since setState is asynchronous the callback function is used for any post action. It is recommended to use lifecycle method rather this callback function.
What happens when you call "setState"?
The first thing React will do when setState is called is merge the object you passed into setState into the current state of the component. This will kick off a process called reconciliation. The end goal of reconciliation is to, in the most efficient way possible, update the UI based on this new state. To do this, React will construct a new tree of React elements (which you can think of as an object representation of your UI). Once it has this tree, in order to figure out how the UI should change in response to the new state, React will diff this new tree against the previous element tree. By doing this, React will then know the exact changes which occurred, and by knowing exactly what changes occurred, will able to minimize its footprint on the UI by only making updates where absolutely necessary.
Explain how spread operator works
The spread operator allows an iterable to spread or expand individually inside a receiver. Iterables are anything that can be looped over such as strings, arrays, and sets. For example — const codeburst = 'CODEBURST'; // Line 1 const characters = [ ...codeburst ]; // Line 2 console.log(characters) // [ 'C', 'O', 'D', 'E', 'B', 'U', 'R', 'S', 'T' ] const letters = [...characters]; console.log(letters) // [ 'C', 'O', 'D', 'E', 'B', 'U', 'R', 'S', 'T' ] The same applies for objects
What happens when you call setState?
The state property in a React component is updated with the object passed into setState, and this is done asynchronously. It tells React that this component and its children need to be re-rendered, but React may not do this immediately (it may batch these state update requests for better performance).
What is virtual DOM?
The virtual DOM (VDOM) is an in-memory representation of Real DOM. The representation of a UI is kept in memory and synced with the "real" DOM. It's a step that happens between the render function being called and the displaying of elements on the screen. This entire process is called reconciliation.
What is Webpack?
Webpack is a module bundling system built on top of Node.js. It can handle not only combination and minification of JavaScript and CSS files, but also other assets such as image files (spriting) through the use of plugins.
What is reconciliation?
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. This process is called reconciliation.
How to pass a parameter to an event handler or callback?
You can use an arrow function to wrap around an event handler and pass parameters: <button onClick={() => this.handleClick(id)} /> This is equivalent to calling .bind as below, <button onClick={this.handleClick.bind(this, id)} />
Where in a React component should you make an AJAX request?
componentDidMount is where an AJAX request should be made in a React component. This method will be executed when the component "mounts" (is added to the DOM) for the first time. This method is only executed once during the component's life. Importantly, you can't guarantee the AJAX request will have resolved before the component mounts. If it doesn't, that would mean that you'd be trying to setState on an unmounted component, which would not work. Making your AJAX request in componentDidMount will guarantee that there's a component to update.
What is Babel?
it's a JavaScript compiler often used to convert JavaScript es6 to earlier versions that is compatible with more browsers. Webpack passed any javascript file it find to the Babel loader, where the content would be transformed from ES6 to ES5