Glossary of React Terms âš›
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
Dictionary:
C:
Context
Provides a way to pass data through the component tree without having to pass props down manually at every level.
Example 🔥
const ThemeContext = React.createContext({ theme: themes.dark,
toggleTheme: () => {},
})
const ThemeTogglerButton = () => {
return (
<ThemeContext.Consumer> {({theme, toggleTheme}) => ( <button
onClick={toggleTheme}
style={{backgroundColor: theme.background}}>
Toggle Theme
</button>
)}
</ThemeContext.Consumer>
)
}
class App extends Component {
state = {
theme: themes.light, toggleTheme: this.toggleTheme, }
this.toggleTheme = () => {
this.setState(state => ({
theme: state.theme === themes.dark ? themes.light : themes.dark,
}))
}
render() {
// The entire state is passed to the provider
return (
<ThemeContext.Provider value={this.state}> <div>
<ThemeTogglerButton />
</div>
</ThemeContext.Provider>
)
}
}
Controlled Components
Uncontrolled Components
React.createRef
Way to access DOM nodes or React elements created in the render method.
Motivations for creating the React.createRef
method in RFC.
Example with focusing text input 🔥
class CustomTextInput extends Component {
constructor(props) {
super(props)
// create a ref to store the textInput DOM element
this.textInput = React.createRef() }
focusTextInput = () => {
this.textInput.current.focus() }
render() {
return (
<div>
<input type="text" ref={this.textInput} /> <input type="button" onClick={this.focusTextInput} />
</div>
)
}
}
Example with React.forwardRef 🔥
const FancyButton = React.forwardRef((props, ref) => ( <button ref={ref} className="FancyButton"> {props.children}
</button>
))
// You can now get a ref directly to the DOM button:
const ref = React.createRef()<FancyButton ref={ref}>Click me!</FancyButton>
Callback Refs
Way that gives more fine-grain control over when refs are set and unset.
Example with focusing text input 🔥
class CustomTextInput extends Component {
constructor(props) {
super(props)
// create a ref to store the textInput DOM element
this.textInput = null this.setTextInputRef = el => this.textInput = el }
focusTextInput = () => {
if (this.textInput) this.textInput.focus() }
render() {
return (
<div>
<input type="text" ref={this.setTextInputRef} /> <input type="button" onClick={this.focusTextInput} />
</div>
)
}
}
Attention:
Without binding the callback
to a class method in the constructor, it calls twice (first time with null
and the second with real value) in render during state updates.
Callback refs are preferable when dealing with dynamic refs.
More examples in react-refs-cheatsheet.
F:
Fiber
New reconciliation
engine. Fiber’s architecture provides a convenient way to track, schedule, pause and abort the work.
Main concept:
RequestIdleCallback
- global function that can be used to queue a function to be called during a browser’s idle periods.
The previos engine used the synchronous recursive model that relied on the built-in stack to walk the tree. Each recursive call adds a frame to the stack. And it does so synchronously.
Fiber offers linked list for getting a opportunity to stop traversal at some point and resume it later. That’s exactly the condition we wanted to achieve to be able to use the new requestIdleCallback
API. Each iltem of list has 3 items: child
, sibling
, return
.
React performs work in two main phases: render (asynchronously) and commit (synchronously).
Render phase
:
React applies updates to components scheduled through setState
or React.render
and figures out what needs to be updated in the UI. The result of the phase is a tree of fiber nodes marked with side-effects
.
Commit phase
:
When React gets to this phase, it has 2 trees (current
, finishedWork
) and the effects list (subset of nodes from the finishedWork
tree linked through the nextEffect
pointer). The whole point of rendering was to determine which nodes need to be inserted, updated, or deleted, and which components need to have their lifecycle methods called. And that’s what the effect list tells us. And it’s exactly the set of nodes that’s iterated during the commit phase.
Read more in article Inside Fiber.
H:
HOCs
Hooks
Are a special functions that let you “hook into” React features.
Hooks let us split the code based on what it is doing rather than a lifecycle method name. React will apply every effect used by the component, in the order they were specified.
useState
Is a Hook that lets you add React state to function components:
🔎 example with useState ...
import React, { useState } from 'react'
const Example = () => {
const [count, setCount] = useState(0)
return (
<div>
<p>You clicked {count} times</p> <button onClick={() => setCount(count + 1)}> Click me
</button>
</div>
)
}
useEffect
By using this Hook, you tell React
that your component needs to do something after render (after performing the DOM updates).
Tip: Unlike componentDidMount
/componentDidUpdate
, effects scheduled with useEffect
don’t block the browser from updating the screen.
React cleans up the previous effects before applying the next effects.
🔎 example with useEffect ...
import React, { useState, useEffect } from 'react'
const FriendStatus = (props) => {
const [isOnline, setIsOnline] = useState(null)
useEffect(() => { const handleStatusChange = (status) => {
setIsOnline(status.isOnline)
}
ChatAPI.subscribeToFriendStatus(props.friend.id, handleStatusChange)
// Specify how to clean up after this effect:
return () => {
ChatAPI.unsubscribeFromFriendStatus(props.friend.id, handleStatusChange)
}
// Only re-subscribe if props.friend.id changes
} [props.friend.id])
if (isOnline === null) {
return 'Loading...'
}
return isOnline ? 'Online' : 'Offline'
}
useContext
Accepts a context object and returns the current context value for that context:
🔎 example with useContext ...
const value = useContext(MyContext)
useReducer
An alternative to useState
. Accepts a reducer of type (state, action) => newState
, and returns the current state paired with a dispatch
method.
🔎 example with useReducer ...
const initialState = { count: 0 }
const reducer = (state, action) => {
switch (action.type) {
case 'increment':
return { count: state.count + 1 }
case 'decrement':
return { count: state.count - 1 }
default:
throw new Error()
}
}
function Counter() {
const [state, dispatch] = useReducer(reducer, initialState)
return (
<>
Count: {state.count}
<button onClick={() => dispatch({type: 'decrement'})}>-</button>
<button onClick={() => dispatch({type: 'increment'})}>+</button>
</>
)
}
useCallback
Returns a memoized version of the callback that only changes if one of the dependencies has changed:
🔎 example with useCallback ...
const memoizedCallback = useCallback(
() => {
doSomething(a, b)
},
[a, b],
)
// useCallback(fn, deps) is equivalent to useMemo(() => fn, deps)
useMemo
Recomputes the memoized value when one of the dependencies has changed. This optimization helps to avoid expensive calculations on every render.
Attention: a function passed to useMemo
runs during rendering. Don’t do anything there that you wouldn’t normally do while rendering, so side effects
belong in useEffect
.
🔎 example with useMemo ...
const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b])
useRef
Returns a mutable ref
object whose .current
property is initialized to the passed argument (initialValue):
🔎 example with useRef ...
const TextInputWithFocusButton = () => {
const inputEl = useRef(null)
const onButtonClick = () => {
// `current` points to the mounted text input element
inputEl.current.focus()
}
return (
<>
<input ref={inputEl} type="text" />
<button onClick={onButtonClick}>Focus the input</button>
</>
)
}
Custom Hook
A function whose name starts with ”use” and that may call other Hooks:
🔎 example of useReducer as Custom hook...
const useReducer = (reducer, initialState) => {
const [state, setState] = useState(initialState)
function dispatch(action) {
const nextState = reducer(state, action)
setState(nextState)
}
return [state, dispatch]
}
K:
Keys
Keys are usually used for dynamic lists. When a key changes, React will create a new component instance rather than update the current one.
L:
React.lazy
API in React to aid in code splitting and importing components into your scripts:
import React, { lazy } from 'react'
const Product = lazy(() => import('./ProductHandler'))
Read more about Suspense.
Lifecycle Methods
Mounting | Updating | Unmounting |
---|---|---|
constructor | static getDerivedStateFromProps | componentWillUnmount |
static getDerivedStateFromProps | shouldComponentUpdate | -- |
render | render | -- |
componentDidMount | getSnapshotBeforeUpdate | -- |
-- | componentDidUpdate | -- |
Error Handling |
---|
static getDerivedStateFromError() |
componentDidCatch() |
Read more about Lifecycle Methods
in react docs.
getDerivedStateFromProps
Is invoked right before calling the render
method. It should return an object to update the state, or null
to update nothing.
Attantion: use componentDidUpdate
for side effects and memoization
for re-compution expensive value in render.
getSnapshotBeforeUpdate
Is invoked right before calling the componentDidUpdate
method. It uses to capture some information from the DOM (e.g. scroll position) before it is potentially changed.
M:
React.memo
MobX
P:
Profiler
Measures how often a React application renders and what the “cost” of rendering is. Its purpose is to help identify parts of an application that are slow and may benefit from optimizations.
PureComponent
Only rerender if at least one state or prop value changes, it performs a shallow comparison of props and state, and reduces the chance that you’ll skip a necessary update.
R:
Recompose
Utility belt for function components and HOCs (pure
, shouldUpdate
). Use React Hooks instead of it.
Redux
Store managment library.
Reconciliation
The process through which React updates the DOM. React then takes tree of components, process it and we get a Virtual DOM. When there is an update in our application (e.g. change in state or props) React will compare the updated Virtual DOM with the old one, then decides what and how should be changed.
Read about new reconciliation engine - Fiber.
Refs
Read more about Callback Refs.
Render props
A technique for sharing code between React components using a prop whose value is a function.
Example with Mouse 🔥
class InnerComponent extends Component {
render() {
const { mouse } = this.props
return (
<div style={{ position: 'absolute', left: mouse.x, top: mouse.y }} />
)
}
}
class Mouse extends Component {
this.state = { x: 0, y: 0 }
handleMouseMove = ({clientX: x, clientY: y}) => {
this.setState({x, y})
}
render() {
return (
<div style={{ height: '100%' }} onMouseMove={this.handleMouseMove}>
{this.props.render(this.state)}
</div>
)
}
}
class App extends Component {
render() {
return (
<div>
<div>lorem</div>
<Mouse render={(mouse) => (
<InnerComponent mouse={mouse} />
)}/>
</div>
)
}
}
Reselect
Library for creating a memoized function for selection data. Might be used for effective data computation from the Redux store (keep in your store minimum data and create derivatives data using selectors).
S:
Suspense
- Suspense is not Component Tree sensitive:
render() {
return(
<div className='product-list'>
<Suspense fallback={<h2>Product is loading...</h2>}>
<p>My product:</p>
<section>
<Product id='1' />
</section>
</Suspense>
</div>
)
}
- We can have nested Suspense objects within other Suspense objects:
MainComponent
Suspense
lazy ProductComponent
Suspense
lazy ProductImageComponent
Suspense
lazy ProductReviewsComponent
ImageComponent
and ReviewsComponent
are independent of each other, and are initiated once ProductComponent
has loaded.
- We can wrap multiple lazily loaded components under one Suspense object.