React Flashcards
(45 cards)
What is the difference between state and props?
Props are immutable, a component’s state shouldn’t be changed from outside that component.
What is React?
React is an open-source JavaScript library created by Facebook for building complex, interactive UIs in web and mobile applications.
What happens during the lifecycle of a React component at a high level?
Initialization, State/Property Updates, Destruction
What are the different component lifecycle methods?
Initialization (getInitialState, getDefaultProps, componentWillMount, render, componentDidMount), Update (componentWillRecieveProps, shouldComponentUpdate, componentWillUpdate, render, componentDidUpdate), Destruction (componentWillUnmount)
What is JSX?
JSX embeds raw HTML templates inside JavaScript(ES2015) code. JSX code by itself cannot be read by the browser; it must be transpiled into traditional JavaScript using tools like Babel and webpack. JSX is not required to use React.
What is Flux?
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. (Action > Dispatch > Store > View). Store is single source of truth.
What are stateless components?
Stateless components (a flavor of “reusable” components) are nothing more than pure functions that render DOM based solely on the properties provided to them. 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.
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.
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).
When would you use a Class Component over a Functional Component?
If your component has state or a lifecycle method(s), use a Class component. Otherwise, use a Functional component.
What are refs in React and why are they important?
Similarly to keys, refs are added as an attribute to a React.createElement() call, such as <li>. The ref serves a different purpose, it provides us quick and simple access to the DOM Element represented by a React Element.
Refs can be either a string or a function. Using a string will tell React to automatically store the DOM Element as this.refs[refValue]
In order to use them as a function 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.</li>
What are keys in React and why are they important?
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. Keys make reconciliation 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.
What is the difference between a controlled component and an uncontrolled component?
In a controlled component, React is the single source of truth for that input fields value and handles its changes. An uncontrolled component lets the DOM handle the field (like vanilla HTML) and we can access that value later with a ref. It’s typically recommended that you favor controlled components over uncontrolled components.
In which lifecycle event do you make AJAX requests and why?
AJAX requests should go in the componentDidMount lifecycle event.
There are a few reasons for this,
Fiber, the new React reconciliation algorithm, has 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.
What does shouldComponentUpdate do and why is it important?
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.
How do you tell React to build in Production mode and what will that do?
Typically you’d use Webpack’s DefinePlugin method to set NODE_ENV to production. This will strip out things like propType validation and extra warnings. On top of that, it’s also a good idea to minify your code because React uses Uglify’s dead-code elimination to strip out development only code and comments, which will drastically reduce the size of your bundle.
Why would you use React.Children.map(props.children, () => ) instead of props.children.map(() => )
It’s not guaranteed that props.children will be an array. React only makes props.children an array if there are more than one child elements. You want to favor React.Children.map because its implemention takes into account that props.children may be an array or an object.
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.
What is the difference between createElement and cloneElement?
createElement is what JSX gets transpiled to and is what React uses to create React Elements (object representations of some UI). cloneElement is used in order to clone an element and pass it new props. They nailed the naming on these two
What is the second argument that can optionally be passed to setState and what is its purpose?
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.
What happens if you pass a function into this.setState?
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
Compare and contrast creating React Components in ES5 and ES2015 (also known as ES6)
ES5:
Creating React Components in ES5 uses the React.createClass() method and components can be rendered either inside another React Component or directly in the call to ReactDOM.render().
to set the state to an initial value, create the getInitialState() function on the Component
you can set the default props for the component to have a certain value with the getDefaultProps() method
ES5 version has autobinding
ES6 (ES2015):
Creating React Components in ES6 uses the class ... extends ...
syntax
we have a constructor() that we use to set the initial state
add default props and a display name as properties of the new class created Component.defaultProps = {...}
no autobinding
Explain the standard JavaScript toolchain, transpilation (via Babel or other compilers), JSX, and these items’ significance in recent development. What sort of tools might you use in the build steps to optimize the compiled output React code?
There are a couple primary pillars in the JavaScript toolchain: Dependency Management, Linting, Style-checking, Transpilation, and Compilation, Minification, Source-Mapping.
Style linting - typically a linter like JSCS is used to ensure the source code is following a certain structure and style
Dependency Management - for JavaScript projects, most people use other packages from npm; some plugins exist for build systems (e.g. Webpack) and compilers (e.g. Babel) that allow automatic installation of packages being imported or require()’d
Transpilation - a specific sub-genre of compilation, transpilation involves compiling code from one source version to another, only to a similar runtime level (e.g. ES6 to ES5)
Compilation - specifically separate from transpiling ES6 and JSX to ES5, is the act of including assets, processing CSS files as JSON, or other mechanisms that can load and inject external assets and code into a file. In addition, there are all sorts of build steps that can analyze your code and even optimize it for you.
Minification and Compression - typically part of - but not exclusively controlled by - compilation, is the act of minifying and compressing a JS file into fewer and/or smaller files
Source-Mapping - another optional part of compilation is building source maps, which help identify the line in the original source code that corresponds with the line in the output code (i.e. where an error occurred)
componentWillMount()
Invoked once, both on the client and server, immediately before the initial rendering occurs. If you call setState within this method, render() will see the updated state and will be executed only once despite the state change.