ReactJS Interview Prep

Réussis tes devoirs et examens dès maintenant avec Quizwiz!

What is a pure function?

- they do not attempt to change their inputs. - they always return the same result for the same inputs.

How can state matriculate to its to other components?

If flows downward, it can be passed down through the props of a child component but not upward or laterally.

What is a ternary operator?

It is a conditional if else operator that reads like this: condition ? true : false.

What is a synthetic event?

It is a cross-browser wrapper around the browser's native event. It has the same interface as the browser's native event. If you need the underlying browser event for some reason, use the nativeEvent attribute to get it.

What is a controlled form component in React?

It is a stateful component in which the form input is obtaining its value from the component state (this.state.value). The event handler connected to the input will update the state which will then inform the value of the input element.

What is JSX?

It is a syntax extension to JavaScript. JSX produces React "elements".

What is the event object in a React event handler?

It is a synthetic event.

What is a root DOM node?

It is the DOM node in the HTML file in which your React app will be rendered. In apps built with just React you will usually have one root DOM node but if you integrate React into an existing app you might have many isolated root DOM nodes.

What JS type does JSX represent?

JSX represents objects: const element = ( <h1 className="greeting"> Hello, world! </h1> ); is identical to: // Note: this structure is simplified const element = { type: 'h1', props: { className: 'greeting', children: 'Hello, world!' } }; These objects are called React elements. They are descriptions of what you want to see on screen.

What is the order of the component lifecycle methods when a component is mounting?

MOUNTING: 1.) constructor() 2.) static getDerivedStateFromProps(props, state) 3.) render() 4.) componentDidMount()

Should a component every modify its own props?

NO, props are read only.

Does setState() overwrite your current state object?

No, it merges the object you provide with your current state.

What methods are required in a class component?

Only the render() method.

How does JSX prevent XSS?

React DOM escapes any values embedded in JSX before rendering them. Everything is converted to a string before being rendered.

What is the difference between React elements and browser DOM elements?

React elements are plain objects and are cheap to create. React DOM takes care of updating the DOM to match the React elements.

What is React?

React us a JS library created by Facebook fo developing UI components. It separates the concerns between application logic and view rendering. It is essentially the view of your application. React DOM is the library that allows React to work with the browser DOM.

What is the API for creating a Context object?

const MyContext = React.createContext(defaultValue); When React renders a component that subscribes to this Context object it will read the current context value from the closest matching provider in the tree.

What are the class properties of component classes?

defaultProps - sets the default props for a component class if the props are received as undefined. displayName - changes the component name in debugging messages.

How can you pass a functional component props that tell it not to render itself?

function WarningBanner(props) { if (!props.warn) { return null; } return ( <div className="warning"> Warning! </div> ); }

What should the base constructor of a class component always be called with?

props

What are instance properties of component instances?

props - contains the props that were defined by the caller of this component. state - contains the data specific to this component that may change over time.

What is an example of using an inline if and logical && to render a component conditionally?

return ( <div> <h1>Hello!</h1> {unreadMessages.length > 0 && <h2> You have {unreadMessages.length} unread messages. </h2> } </div> ); This works because in JS, true && expression always evaluates to expresssion and false && expression always evaluates to false.

How should you call setState() to ensure that you can ensure that state is updated properly?

this.setState((state, props) => ({ counter: state.counter + props.increment }));

What 2 other ways can you get around using bind when implementing a handler method?

- By using the experimental public class fields syntax: class LoggingButton extends React.Component { // This syntax ensures `this` is bound within handleClick. // Warning: this is *experimental* syntax. handleClick = () => { console.log('this is:', this); } render() { return ( <button onClick={this.handleClick}> Click me </button> ); } } - Use an arrow function in the callback: class LoggingButton extends React.Component { handleClick() { console.log('this is:', this); } render() { // This syntax ensures `this` is bound within handleClick return ( <button onClick={(e) => this.handleClick(e)}> Click me </button> ); } } The problem with this syntax is that a different callback is created each time its component is rendered. This will result in extra rendering of child components if it is passed as a prop.

What are the types that render() can return?

- React elements - i.e. <MyComponent /> or <div /> - Arrays and fragments. - Portals - String and numbers - these are rendered as text nodes in the DOM. - Booleans or null - Render nothing (mostly exists to support: return test && <Child /> pattern where test is boolean.

What are the syntactic differenes between DOM elements and React elements when handling events?

- React events are named using camelCase rather than lower case. - With JSX you pass a function as the event handler, rather than a string.

How is the select tag different in React?

A JSX select tag contains a value attribute to obtain the selected option. Bonus: You can pass an array into the value attribute allowing you to select multiple options in a select tag.

How is the textarea tag different in React?

A JSX textarea tag accepts a value attribute just like a single line text input.

What is an error boundary?

A React component that catches JS errors anywhere in their child component tree, logs those errors, and displays a fallback UI instead of the component tree that crashed. They catch errors in the lifecycle methods and constructors of the whole tree below them.

What is a key in reference to an element created with the function.prototype.map() method? Why are they important?

A key is a special string attribute you need to include when creating lists of elements. Keys help React identify which items have changed, are added, or are removed. They give the element a stable identity. Keys don't get passed to components!

What is an element variable?

A variable that contains a React Element. These can be returned inside of JSX elements by embedding them in curly braces.

What is conditional rendering?

Adding a conditional statement in the render method and returning different JSX depending on certain conditions.

What is one way to pass props to a deeply nested component without having to prop drill or use context?

An inversion of control where you store the component in a variable and pass it props from the highest order component. You then pass the variable holding the component through the lower level components to its render location.

How should you go about selecting a key attribute for a rendered list of elements?

Choose an ID that uniquely identifies a list item among its siblings. (ID's from data). Using indexes is not recommended for keys if the order of items may change. This can negatively impact performance and may cause issues with component state.

What are the two main types of components in react?

Class and Functional components.

Why should do you need to bind this in the constructor of the component when setting up a callback method?

Class methods are not bound by default in JS. If you refer to a method without() after it, you should bind the method.

What is a component?

Components are basically JS functions. They accept inputs called props and return React elements describing what should appear on the screen.

What is context?

Context provides a way to pass data through the component tree without having to pass props down manually at every level. It is designed to share data that can be considered "global" for a tree of React components, such as the current authenticated user, theme, etc...

What is wrong with this code: class App extends React.Component { render() { return ( <Provider value={{something: 'something'}}> <Toolbar /> </Provider> ); } }

The consumers will re-render every time the Provider re-renders because a new object is always created for value. Instead lift the value into the parent's state so that the Provider only re-renders when its parent component's value state changes.

How are HTML attributes accessed in JSX?

They are accessed using a camelCased alias i.e. class becomes className and tabindex becomes tabIndex.

What does does the class method contextType do?

This lets you consume the nearest current value of that Context type using this.context.

Why JSX?

To separate concerns with loosely coupled units called "components" that contain both. JSX is not absolutely necessary but is recommended because it allows React to show more useful error and warning messages.

What is the order of the component lifecycle methods when a component is unmounting?

UNMOUNTING: 1.) componentWillUnmount()

What is the order of the component lifecycle methods when a component is updating?

UPDATING (upon re-render): 1.) static getDerivedStateFromProps(props, state) 2.) shouldComponentUpdate(nextProps, nextState) 3.) render() 4.) getSnapshotBeforeUpdate(prevProps, prevState) 5.) componentDidUpdate(prevProps, prevState, snapshot)

When should you use context?

When some data needs to be accessible by many components.

Is JSX an expression? If so, what do they evaluate to?

Yes, JSX expressions become regular JS function calls and evaluate to JS objects.

How do you prevent default behavior of an element in React?

You have to explicitly call e.preventDefault()

What is the difference between bind, call and apply?

- function.prototype.bind(obj, args) returns a function that is bound to the first argument and accepts function arguments as the second argument. - call.prototype.apply(obj, args) binds the function to the first argument and calls it immediately with the second argument. - call.prototype.apply(obj, [args]) is the same as call but accepts an array as the second argument.

What are two ways to pass arguments to event handlers?

1.) <button onClick={(e) => this.deleteRow(id, e)}>Delete Row</button> 2.) <button onClick={this.deleteRow.bind(this, id)}>Delete Row</button>

Steps for thinking in a React way when approaching an app.

1.) Break the UI into a component hierarchy. 2.) Build a static version in React (no state involved). 3.) Identify the minimal but complete representation of UI state. 4.) Identify where your state should live. 5.) Add inverse data flow

constructor(props) { super(props); // Don't do this! this.state = { color: props.color }; } What's wrong with this?

1.) It's unnecessary ( you can use this.props.color directly instead) 2.) It creates bugs (updates to the color prop won't be reflected in the state) Only use this pattern if you intentionally want to ignore prop updates.

What two non lifecycle methods can you call from your components?

1.) setState(updater, callback) - enques changes to the component state and tells React that this component and its children need to be re-rendered with the updated state. (it is dangerous to read state directly after setState() call because it only requests a state update; use a callback or componentDidUpdate to ensure state has been updated.) The updater paramater may be a function in which the params are state and props or an object. 2.) forceUpdate(callback) - This will cause render to be called on the component, skipping shouldComponentUpdate(). This will trigger normal lifecycle methods of child components.

What is the order of the component lifecycle methods when a component errors?

1.) static getDerivedStateFromError() 2.) componentDidCatch()

How do you subscribe a function component to a Context object?

<MyContext.Consumer> <FunctionalComponent /> >MyContext.Consumer />

What is the API for creating a Provider?

<MyContext.Provider value={/* some value */} Every Context object comes with a Provider React component that allows consuming components to subscribe to context changes. All consumers that are descendants of a Provider will re-render whenever the Provider's value prop changes.

How do you embed an expression in JSX?

<h1> {name} </h1>, where name is a variable.

What is lifting state up?

Sharing state between two components by moving it up to the closest common ancestor of the components that need it.

What is event pooling?

The SyntheticEvent object will be reused and all properties will be nullified after the callback has been invoked. This is for performance reasons. As such, you cannot access the event in an asynchronous way. If you want to access the event properties in an async way , you should call event.persist() on the event which will remove the synthetic event from the pool and allow event references to be retained by user code.


Ensembles d'études connexes

Wk 7 immune system practice test

View Set

Chapter 4.1: Rise of the Millionaires Information

View Set

Canada physical landscape and culture

View Set

Lesson 1.0 - Insurance Regulation

View Set

Mastering biology chapter 4,5 and 6

View Set

Chapter 17: Postpartum Adaptations and Nursing Care Foundations of Maternal-Newborn & Women's Health Nursing, 7th Edition

View Set

Texas Statutes and Rules Common to Life and Health Insurance

View Set

Psychiatric Mental Health Chapters 1 & 2

View Set

Financial Accounting Test 1 Madeline Brogan

View Set