React is JavaScript library that makes it easy develop UI
- Virtual DOM
- Templating via JSX
- Data handling via
props
- State management via
state
- Event handling via
props
- "Container" components that solve a variety of problems (e.g. Suspense for lazy loading)
JSX is React's templating language. It resembles HTML, but it's really only syntactic sugar for React.createComponent
Elements are the React's basic building blocks (e.g. a div created via JSX). Component's are organized groups of elements that are enhanced via props
, state
, and other components.
You can create components using JavaScripts default function
syntax or you can use class
syntax.
Historically you would use function components for so-called "stateless" components and class components if a component needed state. However with the addition of the "Hooks" API, you can use state
with function components.
Pure components don't have side effects. That means they don't mutate their props. For a given set of props, a pure component will always return the same result.
state
is a special object in React. It's private property on React components and it's used to store data that changes based events, which could be anything from a user typing something into a form to the result of a network request.
props
is special in React. It's not property on React components. It's not private. As a result it's the primary way that React components communicate with each other. Parents pass props to children. Children pass data to their parents via callbacks. That's canonical way communication in React.
state
is private to the component. props
arent
Because state
changes might be made asynchronously
React batches changes and they might be rendered async. That means you can't rely on the current value of state
to calculate the next state
. Using a callback in setState
is way to ensure that this.state
is what you think its going to be when you call this.setState()
In HTML events are handled by attaching "event listeners" to DOM nodes.
In React events are handled by passing callbacks as props to React elements.
If you're using class properties then you don't need to bind your methods. You can use arrow functions to bind functions expressions directly to the class.
const handleClick = () => {}
If you're not using class properties, then you have to bind your methods in the classes constructor:
// Inside the constructor method
this.handleClick = this.handleClick.bind(this)
You create the parameter for the event handler or callback when you declare them. When you call the function, you can pass whatever you want to the parameter:
// Event handler with `value` as its parameter declared in a parent component
handleChange = value => this.setState({value})
// Event handler on a deeply nested component. We can pass any of the components props to the `value` parameter to relay that information to the parent.
handleChange = e => {
const value = e.target.value
this.props.onGreatGrandChildChange(value)
}
React provides a SyntheticEvent
object that has the same specification as the native EventObject
. As a result, you can create an event handler in React, it automatically receive the SyntheticEvent
object and you can access properties like target
preventDefault
and stopPropagation
.
Inline conditional expressions refers to two methods that for using conditional logic inside JSX expressions.
You can either use the ternary operator or you can use the following patterns:
// If `true`, then render expression
{true && expression}
// If `false`, then ignore expression
{false && expression}
In the context of conditional rendering expression
is typically either a string
, React element, or React component.
Key
props are a special prop that React uses to keep track of changes to arrays of React components / elements.
It's required to add the key
prop to each component / element when mapping over arrays of them.
Refs allow you to give your components direct access to individual DOM nodes.
// Basic ref example
class App extends React.Component {
ref = React.createRef();
// Init your refs via componentDidMount
componentDidMount() {
console.log("this.ref: ", this.ref);
console.log("this.ref: ", this.ref.current);
}
// You can also access nodes via the synthetic event object
logNode(e) {
console.log("this.logNode: ", e.target);
}
render() {
return (
<button onClick={this.logNode} ref={this.ref}>
Click Me
</button>
);
}
}
export default App;
Forward refs are components created via React.forwardRef()
. React.forwardRef()
props and a ref as parameters and return React nodes with ref attributes that get passed along to components lower in the React tree.
Don't understand the question. Not high value. Skip.
It's not important. Skip.
The Virtual DOM is a virtual representation of the Real DOM.
React uses the Virtual DOM and a reconiliation (i.e. diffing) algorithm to more efficiently update the Real DOM.
On intital load, React creates the Virtual DOM, stores it in memory, and renders the Real DOM. On application state
changes React creates a new version of the Virtual DOM and compares it with the Virtual DOM stored in memory. If there are any differences between the nodes in the Virtual DOMs, React updates or removes those nodes in the Real DOM.
The Virtual DOM is a representation of the Real DOM that SPA libraries use to more efficiently update the Real DOM.
The Shadow DOM is part of the browser that is used by web components to make their DOM representations private (i.e. they're not accessible via the document).
Reacts new reconiliation algorithm released with React 16.
To make the diffing algorithm more faster and more flexible. It's headline feature is "incremental rendering", which means React will batch renders into chucks to increase rendering speed.
Controlled componenets are components whose props are completely controlled by its parent.
Uncontrolled components are components that have their own state or they receive their props some external source, like an input field in the Real DOM.
Lifting up state refers to a step in the process of building a React app. When more than one component use the same state, you should "lift state up", which means find a common ancestor where state can live for both components or, if there is no common ancestor, create component specifically to hold state for both components.
Render and Commit. The render phase is pure and is not allowed to have side effects. The commit phase is not pure and side effects are allowed.
The main lifecyle methods are:
render()
componentDidMount()
componentDidUpdate()
componentWillUnmount()
static getDerivedStateFromError()
componentDidCatch()
HOCs are components that take components as props and return a new component without changing the component its passed as props.
The key point is they don't change (i.e. mutate) their arguments. They create something new from their arguments and return the new thing.
Context is a React feature that allows you to bypass the standard parent to nested child data flow and broadcast data directly to nested components.
The children
prop is a special prop that tells React to render a component and it's children (if any).
You can think of the children
prop as a placeholder for content. It's similar to the {{yield}}
statement in Handlebars.
props.children can be a string, a React element, a React component, or an array of any of the above.
JSX comment can written using the following syntax
{/* This is a comment */}
{/*
This is a multi-line
comment block
*/}
Calling super(props)
executes the base classes constructor, which allows tge base class to initialize any properties that instances of the base will inherit (via protoype inheritance).
Other Fun Facts:
-
You can’t use
this
in a constructor until after you've called base classes constructor. That means until you callsuper(props)
thethis
keyword is not available inside your React components. -
If you try to access properties of a base class before calling super(props), thet will be
undefined
because if the base's constructor has not been call, then the the properties won't exist yet.
Reconciliation refers to the algorithm React uses to identify differences between copies of the Virtual DOM so that it can efficiently update the Real DOM.
React.lazy()
requires that modules are dynamically loaded and the dynamically loaded modules must resolve to default-exported React component.
First, because class
is reserved word in JavaScript. Second, because the React team decided the convention for JSX attributes should be camel case.
Fragments allow you to render groups of related elements/components without wrapping them in an additional container
Fragments can render more semantic markup. For example, one can avoid rendering a group of table rows without having to wrap them in a container div
.
Portals allow you to render components outside the context of their parent components. You can open a portal to different part of the document and render something.
They are useful in for things like modals.
Stateless components don't use a state
object. Instead they receive props from their parents.
Stateful components use the state
object and rerender on changes to state
You can use prop-types, flow-type, or typescript
- React core library is small and easy to learn
- React only handles the view layer, so you can orchestrate other concerns to suit your needs
- Virtual DOM and Reconciliation can increase site peformance
- React can be rendered server side to play nice with SEO
- React only covers the view layer. You're on your own in terms of routing, advanced state management, network requests, etc.
- Server-Side rendering is possible but it's hard to make work
- Learning React requires learning the React ecosystem, which is vast
- May be harder to implement certain features, like animations
- Configuring a React app can be a nightmare
Error Boundaries are container components provided by React to catch errors inside the Error Boundaries nested React tree.
Not important. Skip.
Use a static type checker. The most popular options are TypeScript and Flow
ReactDOM is a library of methods that allows you to interact with the Real DOM. It's most popular method is render()
, which is used as the entry point for React applications. Other methods exist that solve other problems e.g. hydrate()
is used for SSR and portal()
is used as an escape hatch to append components outside the main React tree.
It's main purpose is to render (and update) React apps. You pass a React component and a reference to a HTML element to render()
and React returns a React tree and a reference to the component. Ther reference is the component for stateful components and null
for stateless components.
There are several ways to apply styles in React. You can:
- Apply them inline via the
styles
prop passing your styles via an object - Use external stylesheets (i.e. the traditional method)
- Use CSS modules, which allows you to scope your css to specific files
- CSS in JS libraries which allow you scope your css to components via JavaScript modules
If the the component hasn't been mounted yet, you will get an error that you can't call setState
on an unmounted component.
If the component has been mounted, then you will end up rendering your components twice, once from setState()
and once again from 'render()'.
No. componentWillMount()
is called before removing a component from the React tree. Calling setState()
makes no sense because the changes will be destroyed when the component unmounts.
This effectively hard codes the state. When React rerenders the changes for hard coded props won't be updated. Use this.props.propName
.
There are several way to conditionally render React components. Some of the more common methods:
- Using
if ... then
logic outside of JSX - Using the ternary operator inside JSX
- Create some rendering logic the is driven by
state
changes
CRA is boilerplate config that allows you to use React without less responsibility for configuration.
It's a good option for more generic projects that don't have special configuration requirements. In those cases, you can start coding your app much faster and avoid the buring time on basic configuration.
*Bold items are considered core / "need to know"
The order for Mounting is:
constructor()
static getDerivedStateFromProps()
render()
componentDidMount()
The order for Updating is:
static getDerivedStateFromProps()
shouldComponentUpdate()
render()
getSnapShotBeforeUpdate()
componentDidUpdate()
The order for Unmounting is:
componentWillUnmount()
The order for Error Handling is:
static getDerivedStateFromError()
componentDidCatch()
React may update via setState()
asyncronously. Therefore, the value of state
when an a plain object is passed to setState
is unreliable as the actual update may happen async.
You can pass an updater
function to setState()
which will force React to execute setState
immediately and update the UI with the value returned from the updater function.
React interprests JSX tags that start with lowercase letters as native DOM nodes. Therefore, React components must be uppercase to be recognized as React components and not React elements.
Use a formatting library. I prefer Prettier; then everyone on the development can use whatever IDE settings they want to develop and Prettier will make sure their code is formatted according the project's guidelines before commiting (assuming use of pre-commit hooks).
Using a function ensures that state
is updated immediately instead of async. In short, it makes the calculating state
more deterministic and therefore more reliable.