Section 1

Preview this deck

componentWillMount()

Front

Star 0%
Star 0%
Star 0%
Star 0%
Star 0%

0.0

0 reviews

5
0
4
0
3
0
2
0
1
0

Active users

1

All-time users

1

Favorites

0

Last updated

6 years ago

Date created

Mar 1, 2020

Cards (38)

Section 1

(38 cards)

componentWillMount()

Front

componentWillMount() is invoked immediately before mounting occurs. It is called before render(), therefore setting state synchronously in this method will not trigger a re-rendering. Avoid introducing any side-effects or subscriptions in this method. This is the only lifecycle hook called on server rendering. Generally, we recommend using the constructor() instead. componentWillMount() { if(!this.props.isLoggedIn){ this.context.router.push('/'); } }

Back

How is state changed in Redux?

Front

The only way to change the state is to emit an action, an object describing what happened. This ensures that neither the views nor the network callbacks will ever write directly to the state. Instead, they express an intent to transform the state. Because all changes are centralized and happen one by one in a strict order, there are no subtle race conditions to watch out for. `

Back

Describe how events are handled in React.

Front

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.

Back

How is React different?

Front

Because React is a small library focused on building UI components, it is necessarily different than a lot of other JavaScript frameworks. 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 in many situations, they come at the cost of flexibility. 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. I recently migrated an application originally written in AngularJS to React, and one of the things I loved most was... By comparing and contrasting React with another library, not only can you demonstrate a deep understanding of React but also position yourself as a strong candidate by highlighting your experience. Be prepared to be asked some follow-up questions as well, such as: Under what circumstances would you choose React over (AngularJS, etc)? If React only focuses on a small part of building UI components, can you explain some pitfalls one might encounter when developing a large application? If you were rewriting an AngularJS application in React, how much code could you expect to re-use?

Back

What is the role of reducers in Redux?

Front

In Redux, reducers are functions (pure) that take the current state of the application and an action and then return a new state. Understanding how reducers work is important because they perform most of the work. Here is a very simple reducer that takes the current state and an action as arguments and then returns the next state: function handleAuth(state, action) { return _.assign({}, state, { auth: action.payload }); } For more complex apps, using the combineReducers() utility provided by Redux is possible (indeed, recommended). It combines all of the reducers in the app into a single index reducer. Every reducer is responsible for its own part of the app's state, and the state parameter is different for every reducer. The combineReducers() utility makes the file structure much easier to maintain. If an object (state) changes only some values, Redux creates a new object, the values that didn't change will refer to the old object and only new values will be created. That's great for performance. To make it even more efficient you can add Immutable.js. const rootReducer = combineReducers({ handleAuth: handleAuth, editProfile: editProfile, changePassword: changePassword });

Back

setState

Front

setState(updater, [callback]) setState() enqueues changes to the component state and tells React that this component and its children need to be re-rendered with the updated state. This is the primary method you use to update the user interface in response to event handlers and server responses. Think of setState() as a request rather than an immediate command to update the component. For better perceived performance, React may delay it, and then update several components in a single pass. React does not guarantee that the state changes are applied immediately. setState() does not always immediately update the component. It may batch or defer the update until later. This makes reading this.state right after calling setState() a potential pitfall. Instead, use componentDidUpdate or a setState callback (setState(updater, callback)), either of which are guaranteed to fire after the update has been applied. If you need to set the state based on the previous state, read about the updater argument below.

Back

In which lifecycle event do you make AJAX requests and why?

Front

AJAX requests should go in the componentDidMount lifecycle event. There are a few reasons for this, Fiber, the next implementation of React's reconciliation algorithm, will have the ability to start and stop rendering as needed for performance benefits. One of the trade-offs of this is that componentWillMount, the other lifecycle event where it might make sense to make an AJAX request, will be "non-deterministic". What this means is that React may start calling componentWillMount at various times whenever it feels like it needs to. This would obviously be a bad formula for AJAX requests. You can't guarantee the AJAX request won't resolve before the component mounts. If it did, that would mean that you'd be trying to setState on an unmounted component, which not only won't work, but React will yell at you for. Doing AJAX in componentDidMount will guarantee that there's a component to update.

Back

Question #2: What happens during the lifecycle of a React component?

Front

High-Level Component Lifecycle At the highest level, React components have lifecycle events that fall into three general categories: Initialization State/Property Updates Destruction Every React component defines these events as a mechanism for managing its properties, state, and rendered output. Some of these events only happen once, others happen more frequently; understanding these three general categories should help you clearly visualize when certain logic needs to be applied. Low-Level Component Lifecycle Within these three general buckets exist a number of specific lifecycle hooks — essentially abstract methods — that can be utilized by any React component to more accurately manage updates. Understanding how and when these hooks fire is key to building stable components and will enable you to control the rendering process (improving performance). Take a look at the diagram above. The events under "Initialization" only happen when a component is first initialized or added to the DOM. Similarly, the events under "Destruction" only happen once (when the component is removed from the DOM). However, the events under "Update" happen every time the properties or state of the component change. For example, components will automatically re-render themselves any time their properties or state change. However, in some cases a component might not need to update — so preventing the component from re-rendering might improve the performance of our application. class MyComponent extends React.Component { // only re-render if the ID has changed! shouldComponentUpdate(nextProps, nextState) { return nextProps.id === this.props.id; } }

Back

The Component Lifecycle

Front

Each component has several "lifecycle methods" that you can override to run code at particular times in the process. Methods prefixed with will are called right before something happens, and methods prefixed with did are called right after something happens. Mounting These methods are called when an instance of a component is being created and inserted into the DOM: constructor() componentWillMount() render() componentDidMount() Updating An update can be caused by changes to props or state. These methods are called when a component is being re-rendered: componentWillReceiveProps() shouldComponentUpdate() componentWillUpdate() render() componentDidUpdate() Unmounting This method is called when a component is being removed from the DOM: componentWillUnmount()

Back

What are "actions" in Redux?

Front

In a nutshell, actions are events. Actions send data from the application (user interactions, internal events such as API calls, and form submissions) to the store. The store gets information only from actions. Internal actions are simple JavaScript objects that have a type property (usually constant), describing the type of action and payload of information being sent to the store. { type: LOGIN_FORM_SUBMIT, payload: {username: 'alex', password: '123456'} } Actions are created with action creators. That sounds obvious, I know. They are just functions that return actions. function authUser(form) { return { type: LOGIN_FORM_SUBMIT, payload: form } } Calling actions anywhere in the app, then, is very easy. Use the dispatch method, like so: dispatch(authUser(form));

Back

What can you tell me about JSX?

Front

When Facebook first released React to the world, they also introduced a new dialect of JavaScript called JSX that embeds raw HTML templates inside JavaScript code. JSX code by itself cannot be read by the browser; it must be transpiled into traditional JavaScript using tools like Babel and webpack. While many developers understandably have initial knee-jerk reactions against it, JSX (in tandem with ES2015) has become the defacto method of defining React components.

Back

What happens when you call setState?

Front

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.

Back

What are keys in React and why are they important?

Front

Keys are what help React keep track of what items have changed, been added, or been removed from a list. It's important that each key be unique among siblings. We've talked a few times already about reconciliation and part of this reconciliation process is performing a diff of a new element tree with the most previous one. Keys make this process more efficient when dealing with lists because React can use the key on a child element to quickly know if an element is new or if it was just moved when comparing trees. And not only do keys make this process more efficient, but without keys, React can't know which local state corresponds to which item on move. So never neglect keys when mapping.

Back

What's the difference between an Element and a Component in React?

Front

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).

Back

componentWillUnmount

Front

componentWillUnmount() is invoked immediately before a component is unmounted and destroyed. Perform any necessary cleanup in this method, such as invalidating timers, canceling network requests, or cleaning up any DOM elements that were created in componentDidMount

Back

What is React?

Front

React is an open-source JavaScript library created by Facebook for building complex, interactive UIs in web and mobile applications. The key point in this answer is that React's core purpose is to build UI components; it is often referred to as just the "V" (View) in an "MVC" architecture.

Back

shouldComponentUpdate()

Front

shouldComponentUpdate(nextProps, nextState) Use shouldComponentUpdate() to let React know if a component's output is not affected by the current change in state or props. The default behavior is to re-render on every state change, and in the vast majority of cases you should rely on the default behavior. shouldComponentUpdate() is invoked before rendering when new props or state are being received. Defaults to true. This method is not called for the initial render or when forceUpdate() is used. Returning false does not prevent child components from re-rendering when their state changes. Currently, if shouldComponentUpdate() returns false, then componentWillUpdate(), render(), and componentDidUpdate() will not be invoked. Note that in the future React may treat shouldComponentUpdate() as a hint rather than a strict directive, and returning false may still result in a re-rendering of the component.

Back

Flux Difference with AngularJS (1.x)

Front

UI components in AngularJS typically rely on some internal $scope to store their data. This data can be directly mutated from within the UI component or anything given access to $scope — a risky situation for any part of the component or greater application which relies on that data. By contrast, the Flux pattern encourages the use of immutable data. Because the store is the central authority on all data, any mutations to that data must occur within the store. The risk of data pollution is greatly reduced.

Back

What does shouldComponentUpdate do and why is it important?

Front

Above we talked about reconciliation and what React does when setState is called. What shouldComponentUpdate does is it's a lifecycle method that allows us to opt out of this reconciliation process for certain components (and their child components). Why would we ever want to do this? As mentioned above, "The end goal of reconciliation is to, in the most efficient way possible, update the UI based on new state". If we know that a certain section of our UI isn't going to change, there's no reason to have React go through the trouble of trying to figure out if it should. By returning false from shouldComponentUpdate, React will assume that the current component, and all its child components, will stay the same as they currently are.

Back

What is React?

Front

React is an open-source JavaScript library created by Facebook for building complex, interactive UIs in web and mobile applications. The key point in this answer is that React's core purpose is to build UI components; it is often referred to as just the "V" (View) in an "MVC" architecture. Therefore it has no opinions on the other pieces of your technology stack and can be seamlessly integrated into any application.

Back

What are stateless components?

Front

Stateless components (a flavor of "reusable" components) are nothing more than pure functions that render DOM based solely on the properties provided to them. const StatelessCmp = (props) => { return ( <div className="my-stateless-component"> {props.name}: {props.birthday} </div> ); }; // --- ReactDOM.render( <StatelessCmp name="Art" birthday="10/01/1980" />, document.getElementById("main") ); As you can see, this component has no need for any internal state — let alone a constructor or lifecycle handlers. The output of the component is purely a function of the properties provided to it.

Back

Flux vs MVC

Front

Traditional MVC patterns have worked well for separating the concerns of data (Model), UI (View) and logic (Controller) — but many web developers have discovered limitations with that approach as applications grow in size. Specifically, MVC architectures frequently encounter two main problems: Poorly defined data flow: The cascading updates which occur across views often lead to a tangled web of events which is difficult to debug. Lack of data integrity: Model data can be mutated from anywhere, yielding unpredictable results across the UI. With the Flux pattern complex UIs no longer suffer from cascading updates; any given React component will be able to reconstruct its state based on the data provided by the store. The flux pattern also enforces data integrity by restricting direct access to the shared data.

Back

Why would you use React.Children.map(props.children, () => ) instead of props.children.map(() => )

Front

It's not guaranteed that props.children will be an array. Take this code for example, <Parent> <h1>Welcome.</h1> </Parent> Inside of Parent if we were to try to map over children using props.children.map it would throw an error because props.children is an object, not an array. React only makes props.children an array if there are more than one child elements, like this <Parent> <h1>Welcome.</h1> <h2>props.children will now be an array</h2> </Parent> This is why you want to favor React.Children.map because its implemention takes into account that props.children may be an array or an object.

Back

componentWillReceiveProps()

Front

componentWillReceiveProps(nextProps) componentWillReceiveProps() is invoked before a mounted component receives new props. If you need to update the state in response to prop changes (for example, to reset it), you may compare this.props and nextProps and perform state transitions using this.setState() in this method. Note that React may call this method even if the props have not changed, so make sure to compare the current and next values if you only want to handle changes. This may occur when the parent component causes your component to re-render. React doesn't call componentWillReceiveProps with initial props during mounting. It only calls this method if some of component's props may update. Calling this.setState generally doesn't trigger componentWillReceiveProps.

Back

What is wrong with this code? this.setState((prevState, props) => { return { streak: prevState.streak + props.count } })

Front

Nothing is wrong with it 🙂. It's rarely used and not well known, but you can also pass a function to setState that receives the previous state and props and returns a new state, just as we're doing above. And not only is nothing wrong with it, but it's also actively recommended if you're setting state based on previous state.

Back

constructor()

Front

The constructor for a React component is called before it is mounted. When implementing the constructor for a React.Component subclass, you should call super(props) before any other statement. Otherwise, this.props will be undefined in the constructor, which can lead to bugs. The constructor is the right place to initialize state. If you don't initialize state and you don't bind methods, you don't need to implement a constructor for your React component. It's okay to initialize state based on props. This effectively "forks" the props and sets the state with the initial props. Here's an example of a valid React.Component subclass constructor: constructor(props) { super(props); this.state = { color: props.initialColor }; } Beware of this pattern, as state won't be up-to-date with any props update. Instead of syncing props to state, you often want to lift the state up.

Back

componentDidUpdate

Front

componentDidUpdate(prevProps, prevState) componentDidUpdate() is invoked immediately after updating occurs. This method is not called for the initial render. Use this as an opportunity to operate on the DOM when the component has been updated. This is also a good place to do network requests as long as you compare the current props to previous props (e.g. a network request may not be necessary if the props have not changed).

Back

When would you use a Class Component over a Functional Component?

Front

If your component has state or a lifecycle method(s), use a Class component. Otherwise, use a Functional component.

Back

Description of Flux

Front

In the Flux pattern, the Store is the central authority for all data; any mutations to the data must occur within the store. Changes to the Store data are subsequently broadcast to subscribing Views via events. Views then update themselves based on the new state of received data. To request changes to any Store data, Actions may be fired. These Actions are controlled by a central Dispatcher; Actions may not occur simultaneously, ensuring that a Store only mutates data once per Action. The strict unidirectional flow of this Flux pattern enforces data stability, reducing data-related runtime errors throughout an application.

Back

Are you familiar with Flux?

Front

Flux is an architectural pattern that enforces unidirectional data flow — its core purpose is to control derived data so that multiple components can interact with that data without risking pollution. The Flux pattern is generic; it's not specific to React applications, nor is it required to build a React app. However, Flux is commonly used by React developers because React components are declarative — the rendered UI (View) is simply a function of state (Store data). action -> dispatcher -> store -> view

Back

componentDidMount()

Front

componentDidMount() is invoked immediately after a component is mounted. Initialization that requires DOM nodes should go here. If you need to load data from a remote endpoint, this is a good place to instantiate the network request. Setting state in this method will trigger a re-rendering.`

Back

What are refs in React and why are they important?

Front

Refs are an escape hatch which allow you to get direct access to a DOM element or an instance of a component. In order to use them you add a ref attribute to your component whose value is a callback function which will receive the underlying DOM element or the mounted instance of the component as its first argument. class UnControlledForm extends Component { handleSubmit = () => { console.log("Input Value: ", this.input.value) } render () { return ( <form onSubmit={this.handleSubmit}> <input type='text' ref={(input) => this.input = input} /> <button type='submit'>Submit</button> </form> ) } } Above notice that our input field has a ref attribute whose value is a function. That function receives the actual DOM element of input which we then put on the instance in order to have access to it inside of the handleSubmit function. It's often misconstrued 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. function CustomForm ({handleSubmit}) { let inputElement return ( <form onSubmit={() => handleSubmit(inputElement.value)}> <input type='text' ref={(input) => inputElement = input} /> <button type='submit'>Submit</button> </form> ) }

Back

What is the concept of "single source of truth" in Redux?

Front

The state of your whole application is stored in an object tree within a single store. This makes it easy to create universal apps, as the state from the server can be serialized and hybridized into the client with no extra coding effort. A single state tree also makes it easier to debug or introspect an application; it also enables persisting the app's state in development, for a faster development cycle.

Back

What is 'Store' in Redux?

Front

Store is the object that holds the application state and provides a few helper methods to access the state, dispatch actions and register listeners. The entire state is represented by a single store. Any action returns a new state via reducers. That makes Redux very simple and predictable.

Back

componentWillUpdate()

Front

componentWillUpdate(nextProps, nextState) componentWillUpdate() is invoked immediately before rendering when new props or state are being received. Use this as an opportunity to perform preparation before an update occurs. This method is not called for the initial render. Note that you cannot call this.setState() here. If you need to update state in response to a prop change, use componentWillReceiveProps() instead. Note componentWillUpdate() will not be invoked if shouldComponentUpdate() returns false.

Back

render()

Front

The render() method is required. When called, it should examine this.props and this.state and return a single React element. This element can be either a representation of a native DOM component, such as <div />, or another composite component that you've defined yourself. You can also return null or false to indicate that you don't want anything rendered. When returning null or false, ReactDOM.findDOMNode(this) will return null. The render() function should be pure, meaning that it does not modify component state, it returns the same result each time it's invoked, and it does not directly interact with the browser. If you need to interact with the browser, perform your work in componentDidMount() or the other lifecycle methods instead. Keeping render() pure makes components easier to think about. render() will not be invoked if shouldComponentUpdate() returns false.

Back

What is the second argument that can optionally be passed to setState and what is its purpose?

Front

A callback function which will be invoked when setState has finished and the component is re-rendered. Something that's not spoken of a lot is that setState is asynchronous, which is why it takes in a second callback function. Typically it's best to use another lifecycle method rather than relying on this callback function, but it's good to know it exists. this.setState( { username: 'tylermcginnis33' }, () => console.log('setState has finished and the component has re-rendered.') )

Back

What is the difference between a controlled component and an uncontrolled component?

Front

A large part of React is this idea of having components control and manage their own state. What happens when we throw native HTML form elements (input, select, textarea, etc) into the mix? Should we have React be the "single source of truth" like we're used to doing with React or should we allow that form data to live in the DOM like we're used to typically doing with HTML form elements? These two questions are at the heart of controlled vs uncontrolled components. A controlled component is a component where React is in control and is the single source of truth for the form data. As you can see below, username doesn't live in the DOM but instead lives in our component state. Whenever we want to update username, we call setState as we're used to. class ControlledForm extends Component { state = { username: '' } updateUsername = (e) => { this.setState({ username: e.target.value, }) } handleSubmit = () => {} render () { return ( <form onSubmit={this.handleSubmit}> <input type='text' value={this.state.username} onChange={this.updateUsername} /> <button type='submit'>Submit</button> </form> ) } } An uncontrolled component is where your form data is handled by the DOM, instead of inside your React component. You use refs to accomplish this. class UnControlledForm extends Component { handleSubmit = () => { console.log("Input Value: ", this.input.value) } render () { return ( <form onSubmit={this.handleSubmit}> <input type='text' ref={(input) => this.input = input} /> <button type='submit'>Submit</button> </form> ) } } Though uncontrolled components are typically easier to implement since you just grab the value from the DOM using refs, it's typically recommended that you favor controlled components over uncontrolled components. The main reasons for this are that controlled components support instant field validation, allow you to conditionally disable/enable buttons, enforce input formats, and are more "the React way".

Back