Main Concepts Flashcards
What is the smallest React example?
ReactDOM.render(
< h1 >Hello, world!< /h1 >,
document.getElementById(‘root’)
);
What is this an example of?
const element = < h1 >Hello, world!< /h1 >;
JSX.
What is React?
A JavaScript library for building user interfaces.
What is JSX?
A syntax extension to JavaScript.
How is JSX not like a template language?
Because it comes with the full power of JavaScript.
What does JSX produce?
React elements.
What does React embrace?
The fact that rendering logic is inherently coupled with other UI logic: how events are handled, how the state changes over time, and how the data is prepared for display.
What would React do instead of artificially separating technologies by putting markup and logic in separate files?
Separates concerns with loosely coupled units called “components” that contain both.
Does React require JSX?
No.
How do people find JSX useful?
As a visual aid when working with UI inside the JavaScript code.
What does JSX allow React to do?
To show more useful error and warning messages.
Declare a variable called name and then use it inside JSX by wrapping it in curly braces.
const name = 'Josh Perez'; const element = < h1 >Hello, { name }< /h1 >;
ReactDOM.render(
element,
document.getElementById(‘root’)
);
What can you put inside the curly braces in JSX?
Any valid JavaScript expression.
How can we make JSX more readable?
By splitting it over multiple lines.
What should you also do when splitting JSX over multiple lines and why?
Wrapping it in parentheses to avoid the pitfalls of automatic semicolon insertion.
What happens to JSX after compilation?
They become regular JavaScript function calls and evaluate to JavaScript objects.
What does JSX being compiled mean?
You can use JSX inside of if statements and for loops, assign it to variables, accept it as arguments, and return it from functions.
Show JSX being used inside an if statement.
function getGreeting(user) { if (user) { return < h1 >Hello, { formatName(user) }!< /h1 >; } return < h1 >Hello, Stranger.< /h1 >; }
How would you specify string literals as attributes?
By using quotes.
Show an example of using quotes to specify string literals as attributes.
const element = < div tabIndex=”0” >< /div >;
How would you embed a JavaScript expression in an attribute?
By using curly braces.
Show an example of using curly braces to embed a JavaScript expression in an attribute.
const element = < img src={ user.avatarUrl } >< /img >;
What should you note about using quotes (for string values) or curly braces (for expressions) in attributes.
You should use one or the other, not both at the same time.
What naming convention is used for JSX?
camelCase.
Show an example of JSX tags containing children.
const element = ( < div > < h1 >Hello!< /h1 > < h2 >Good to see you here.< /h2 > < /div > );
Is it safe to embed user input in JSX?
Yes.
Show an example of embedding user input in JSX.
const title = response.potentiallyMaliciousInput; // This is safe: const element = < h1 >{ title }< /h1 >;
What does ReactDOM do by default with values embedded in JSX?
Escapes them before rendering them.
What does React DOM escaping any values embedded in JSX before rendering them ensure?
You can never inject anything that’s not explicitly written in your application. Everything is converted to a string before being rendered.
What does React DOM escaping any values embedded in JSX before rendering help prevent?
XSS (cross-site-scripting) attacks.
What does Babel compile JSX down to?
React.createElement() calls.
What would this code look like when run through Babel?
const element = ( < h1 className="greeting" > Hello, world! < /h1 > );
const element = React.createElement( 'h1', { className: 'greeting' }, 'Hello, world!' );
What does React.createElement() perform.
A few checks to help you write bug-free code but essentially it creates an object like this:
// Note: this structure is simplified const element = { type: 'h1', props: { className: 'greeting', children: 'Hello, world!' } };
What are the objects created from React.createElement() called?
React elements.
What can you think of React elements as?
Descriptions of what you want to see on the screen. React reads these objects and uses them to construct the DOM and keep it up to date.
What does a element describe?
What you want to see on the screen.
How do DOM elements differ from React elements?
They’re plain objects, and are cheap to create.
What takes care of updating the DOM to match the React elements.
React DOM.
What are elements?
They’re what components are made up of.
What is a “root” DOM node?
A node where everything inside it will be managed by React DOM.
How many root DOM nodes does a React application have?
Usually one, unless you are integrating React into an existing app, then you may have as many isolated root DOM nodes as you like.
Ho do you render a React element into a root DOM node?
Pass both to ReactDOM.render().
Show an example of rendering a React element into a root DOM node?
const element = < h1 >Hello, world< /h1 >; ReactDOM.render(element, document.getElementById('root'));
What does it mean that React elements are immutable?
Once you create an element, you can’t change its children or attributes.
Whats a good way of thinking about an element?
As a single frame in a movie: it represents the UI at a certain point in time.
How many times do React apps usually call ReactDOM.render()
Once.
What does React DOM do after it compares the element and its children to the previous one?
Only applies the DOM updates necessary to bring the DOM to the desired state.
How can you verify that React DOM only applies the DOM updates necessary to bring the DOM to the desired state?
by inspecting the last example with the browser tools.
What do components let you do?
Split the UI into independent, reusable pieces, and think about each piece in isolation.
Conceptually, what are components like?
JavaScript functions.
What do components accepts and return?
They accept arbitrary inputs (called “props”) and return React elements describing what should appear on the screen.
What is the simplest way to define a component?
By writing a JavaScript function.
Write a simple component as a JavaScript function.
function Welcome(props) { return < h1 >Hello, { props.name }< /h1 >; }
Why is this function a valid React component?
function Welcome(props) { return < h1 >Hello, { props.name }< /h1 >; }
Because it accepts a single “props” (which stands for properties) object argument with data and returns a React element.
What do we call this type of component?
function Welcome(props) { return < h1 >Hello, { props.name }< /h1 >; }
A “function component” because they are literally JavaScript functions.
How would you use an ES6 class to define a function component?
class Welcome extends React.Component { render() { return < h1 >Hello, { this.props.name }< /h1 >; } }
Show an example of an element that can also represent user-defined components.
const element = < Welcome name=”Sara” / >;
What does React do when it sees an element representing a user-defined component?
It passes JSX attributes to this component as a single object called “props”.
How should you always start a components name?
With a capital letter.
Why should you always start a components name with a capital letter?
Because React treats components starting with lowercase letters as DOM tags. For example, < div / > represents an HTML div tag, but < Welcome / > represents a component and requires Welcome to be in scope.
What does components referring to other components in their output allow?
To use the same component abstraction for any level of detail.
In React how is a button, a form, a dialog, a screen, commonly expressed as?
Components.
Typically, what do new React apps have at the very top?
A single App component. However, if you integrate React into an existing app, you might start bottom-up with a small component like Button and gradually work your way to the top of the view hierarchy.
When is it a good idea to have reusable components?
If a part of your UI is used several times, or is complex enough on its own.
What should you never do whether you declare a component as a function or a class?
Modify its own props.
What is Reacts single strict rule?
All React components must act like pure functions with respect to their props.
What does State allow in React components?
To change their output over time in response to user actions, network responses, and anything else, without violating Reacts single strict rule.
How is state different to props?
It’s private and fully controlled by the component.
How can you convert a function component to a class?
Create an ES6 class, with the same name, that extends React.Component.
Add a single empty method to it called render().
Move the body of the function into the render() method.
Replace props with this.props in the render() body.
Delete the remaining empty function declaration.
When does the render method get called?
(at the start) and each time an update happens.
What are some examples of additional features converting a …. function to a class give us access to?
Using local state and lifecycle methods.
How could you move ‘date’ from props to state?
Replace this.props.date with this.state.date in the render() method.
Add a class constructor that assigns the initial this.state
Note how we pass props to the base constructor.
Class components should always call the base constructor with props.
Remove the date prop from the element.
What do you do in applications when components are destroyed?
Free up resources they take.
What is it called when something is rendered to the DOM for the first time?
Mounting.
What is it called when you want to clear something whenever the DOM produced by ……… is removed?
Unmounting.
How would you mount and unmount some code?
By declaring special methods on the component class called componentDidMount() and componentWillUnmount()
What are componentDidMount() and componentWillUnmount() examples of?
Lifecycle methods.
When does the componentDidMount() method run?
After the component output has been rendered to the DOM.
What should you not do with state?
Modify it directly.
How should you modify state?
By using setState()
Where do you put this.state?
In the constructor.
What might React do in regards to setState() calls for performance?
Batch multiple calls into a single update.
Why shouldn’t you rely on this.props and this.state values for calculating the next state?
Because they may be updated asynchronously.
Because this.props and this.state may be updated asynchronously, what’s a better way of calculating state?
Use a second form of setState() that accepts a function rather than an object. That function will receive the previous state as the first argument, and the props at the time the update is applied as the second argument:
How would you convert this code to make sure counter is the correct value?
this.setState( {
counter: this.state.counter + this.props.increment,
} );
this.setState((state, props) => ( {
counter: state.counter + props.increment
} ));
How would you convert this arrow function to a regular function?
this.setState((state, props) => ( {
counter: state.counter + props.increment
} ));
this.setState(function(state, props) { return { counter: state.counter + props.increment }; } );
What happens when you call setState()
React merges the object you provide into the current state.
What happens when your state contain several independent variables, and you update them independently with separate setState() calls?
The merging is shallow, so this.setState({x}) leaves this.state.y intact, but completely replaces this.state.x
How can a parent or child component know if a certain component is stateful or stateless?
They can’t and they shouldn’t care whether it is defined as a function or a class.
Why is state often called local or encapsulated?
It’s not accessible to any component other than the one that owns and sets it.
How can a component pass its sate down to its child components?
As props.
< FormattedDate date={ this.state.date } / >
How would The FormattedDate component (that receives the date in its props) know where it came from?
It wouldn’t know whether it came from the Clock’s state, from the Clock’s props, or was typed by hand.
What does it mean when something has a “top-down” or “unidirectional” data flow?
Any state is always owned by some specific component, and any data or UI derived from that state can only affect components “below” them in the tree.
If you imagine a component tree as a waterfall of props, continue the analogy for state.
Each component’s state is like an additional water source that joins it at an arbitrary point but also flows down.
In React apps, what is it considered when a component is stateful or stateless?
An implementation detail of the component that may change over time. You can use stateless components inside stateful components, and vice versa.
What are some syntactic differences when handling events with React elements vs handling events on DOM elements?
React events are named using camelCase, rather than lowercase.
With JSX you pass a function as the event handler, rather than a string.
Convert this to a React implementation.
< button onclick=”activateLasers()” >
Activate Lasers
< /button >
< button onClick={ activateLasers } >
Activate Lasers
< /button >
How would you prevent default behavior in React?
You can’t return false. You must call preventDefault explicitly.
with plain HTML, to prevent the default link behavior of opening a new page, you can write.
< a href=”#” onclick=”console.log(‘The link was clicked.’); return false” >
Click me
< /a >
How would you do this in React?
function ActionLink() { function handleClick(e) { e.preventDefault(); console.log('The link was clicked.'); }
return ( < a href="#" onClick={handleClick} > Click me < /a > ); }