react

React

October 02, 2022

React

Yuri Kim


React

A JavaScript library developed by Facebook for building user interfaces. React uses a component-based architecture to create interfaces with an intuitive declarative approach.

__

Component

A reusable independent piece of a user interface. In modern React, components are usually functional components, which are simply functions that return JSX.

__

JSX

Short for JavaScript XML, a JavaScript syntax extension for inlining XML and HTML in JavaScript. For example, this code could be compiled into standard JavaScript function calls to create a heading element:

const h1 = <h1>Hello World</h1>;
__

ReactDOM

A package used with React to work as the bridge between React elements and the actual DOM in the browser. The most frequently used ReactDOM function is the render function, which adds a component to the DOM. For example:

ReactDOM.render( <h1>Hello World</h1>, document.getElementById('root') );
__
__

JSX

React.Fragment

A React container component that renders its children without adding any additional DOM nodes. This can be used for returning multiple adjacent elements without wrapping them in an unnecessary element. For example:

<React.Fragment> <h1>Hello World</h1> <p>React is awesome!</p> </React.Fragment>

Fragments can also be created by using an empty tag, rather than the Fragment export from React. For example:

<> <h1>Hello World</h1> <p>React is Awesome!</p> </>
__

Conditional Rendering

The process of changing the returned element of a component based on some condition. Conditional rendering can be achieved in a variety of ways, but the most common utilizes ternary operators or short circuit evaluation. This works because null, undefined, true and false all do not render anything:

<React.Fragment> { myBool ? <h1>Hello World</h1> : null } { myOtherBool && <p>React is Awesome!</p> } </React.Fragment>
__
__

Props

A JavaScript object passed as a parameter to functional components, containing all of the key-value pairs that were passed as attributes to the component. For example, given this JSX:

<MyComponent message="hello" number={42} />

The MyComponent function would take in props with two key-value pairs:

function MyComponent(props) { console.log(props.message); // "hello" console.log(props.number); // 42 return <h1>Hello World!</h1>; }
__
__

Event-Driven Programming

SyntheticEvent

The object type passed to React event handler functions. Synthetic events generally work the same as native events, but with more consistency across browsers.

__
__

State

Data specific to an instance of a component that persists between renders and causes re-renders when changed.

__

Hook

A JavaScript function used to "hook" into React features such as state and the larger component lifecycle. The names of hooks always begin with use, and they cannot be called conditionally.

__

useState

A React hook for creating stateful components. The useState function takes in an initial state value (or a function that returns that initial value), and it returns an array with two elements: the current state value and a setter function. For example:

const [number, setNumber] = useState(42);
__

useReducer

An alternative React hook for creating stateful components, oftentimes used for more complex state. The useReducer function takes in a reducer function and the initial state. It returns an array with two elements: the current state value and a dispatch function.

__

The reducer function takes in the previous state and an action object as parameters, then it returns the new state. Usually the action object will have a type property, which will be used in a switch statement. For example:

function reducer(state, action) { switch (action.type) { case 'increment': return {count: state.count + action.num}; case 'decrement': return {count: state.count - action.num}; default: throw new Error('Unknown action type'); } }

The dispatch function will then take in an object, which will be passed as the action to the reducer function. For example:

const [state, dispatch] = useReducer(reducer, { count: 0 }); return ( <button onClick={() => dispatch({ type: 'increment', num: 1 })}>Increment</button>);

Lifting State Up

A common React pattern of moving shared state up to the lowest common ancestor component in the tree. This allows for a single component to keep track of the state and pass the current value and setter function down through props.

__

Controlled Component

A pattern of using React state to control the current state of an input, rather than allowing the native elements to control their own state (known as an uncontrolled component). For example, an input can be controlled via the value and onChange props (note that in React, onChange works the same as onInput). For example:

const [value, setValue] = useState(''); return <input value={value} onChange={e => setValue(e.target.value)} />;
__
__

Component Lifecycle

The different stages that an instance of a component goes through. There are three primary stages to the React lifecycle:

  1. Mounting: The component renders for the first time.
  2. Updating: The component re-renders whenever state changes or the props are updated by the parent component. A component can update many times without ever mounting again.
  3. Unmounting: The component is removed from the DOM. This is the final stage of the lifecycle, and a component cannot update again once it has been unmounted. However, a new instance of the component can still be mounted.
__

useEffect

A React hook for performing side effects around the component lifecycle. The useEffect hook takes in a callback function and an optional dependency array.

__

If no dependency array is provided, the callback function will run on every render. If there is a dependency array provided, the callback function will only run on mount or when an item in that array has changed (note that objects must be new objects to be considered to have changed). To avoid bugs related to effects using stale values from previous renders, the dependency array should contain all values that the callback uses that could change between renders.

__

The callback function can also return a cleanup function, which will run on unmount and before the main effect function runs on any re-renders. For example:

useEffect(() => { console.log('count changed'); return () => console.log('cleanup count changed effect'); }, [count]);
__

useLayoutEffect

A React hook for performing side effects around the component lifecycle in the same way as useEffect. The only difference between the two functions is that useLayoutEffect works synchronously, meaning the effects always finish running before the browser paints. This hook should only be used for effects that will make visual changes to the DOM, because otherwise the synchronous nature will give worse performance than useEffect without any benefits.

__
__

Refs

A React value specific to an instance of a component that persists between renders, but updating the value does not cause a re-render (unlike state). Refs are oftentimes used to reference the DOM node associated with the component, which can be achieved with the ref attribute.

__

useRef

A React hook for creating a ref. The useRef hook takes in an initial value and returns a ref. The ref is simply an object with a current property set to the current value.

const div = useRef(null); return <div ref={div}>This div has a ref</div>;
__

React.forwardRef

A function used by a custom component to forward a ref attribute on to a child element. The forwardRef function is a higher-order component function, meaning it takes in a component and returns a new one. In this case, it takes a component that has a second parameter for the ref. For example:

`function Parent() { const ref = useRef(null); return <Child ref={ref}>This child has a ref</Child>; }

const child = forwardRef(function (props, ref) { return <div ref={ref}>{props.children}</div>; });`
__
__

Imperative React

useImperativeHandle

A React hook for customizing the value provided to a parent component when using a ref. The useImperativeHandle hook takes in a ref as the first parameter, followed by a callback function and an optional dependency array.

__

The return value of the callback function will act as the current value of the ref. If any item in the dependency array changes between renders, the callback function will be invoked again to recalculate the current value.

__

Since useImperativeHandle requires a ref on a custom component, it should always be used with React.forwardRef. For example:

`forwardRef(function (props, ref) { const [count, setCount] = useState(0);

useImperativeHandle(ref, () => { return { resetCount: () => setCount(0) }; });

return ( <button onClick={() => setCount(count + 1)}> Increment </button>); }`
__
__

Contexts

Context

A way to pass values down a component tree without needing to pass props through every component (known as prop drilling). Contexts are generally useful for global state needed throughout an application or page, which would be inconvenient to pass as props to every element needing it.

__

React.createContext

A react function for creating a context object. This function takes in a default value, which will be used if there is no matching context provider in a tree. For example, this would create a context that could be used to keep track of a user's selected theme:

const ThemeContext = createContext({ mode: 'dark' });

This context would then have a provider component, which must be above any components in the tree that wish to use the context. The value prop will be passed as the value to all children using the context. For example:

return ( <ThemeContext.Provider value={{mode: 'dark'}}> {props.children} </ThemeContext.Provider>);
__

useContext

A React hook for using a context. The useContext function takes in a context object created with createContext, and it returns the value from the first context provider of that context above it in the tree. For example:

const theme = useContext(ThemeContext); console.log(theme.mode); // 'dark'
__
__

Component Lists

Key Prop

A prop passed to each element in a list to help React keep track of those elements. Key props should be unique identifiers. By passing key props, if the list changes, React can easily know which elements need to be mounted, updated, and unmounted. For example, when rendering an array of messages from the server, message IDs could be used as a key prop:

return ( { messages.map(message => { return <p key={message.id}>{message.text}</p>; }); } );
__
__

Performance

useMemo

A React hook for memoizing a value. The useMemo function takes in a function that returns a value to be memoized and a dependency array. The useMemo function then returns the memoized value, and it only calls the passed in function to recalculate the value if an item in the dependency array changes. For example:

const value = useMemo(() => slowFunction(x, y), [x, y]);
__

useCallback

A React hook for memoizing a function. This function works the exact same as useMemo, except rather than memoizing the return value of a function, it memoizes the entire function. This can be useful for a variety of reasons, such as if a callback is passed into a dependency array that requires it to not change on every render. For example:

const callback = useCallback(() => console.log(x, y), [x, y]);
__

React.memo

A React higher-order component that takes in a component and returns a memoized version of that component. If the props have not changed, wrapping a component in React.memo will cause it to avoid re-rendering. This function can optionally also take in a second callback function as a parameter to determine when the component should re-render with more fine control. For example, this component will only need to re-render when the number prop changes:

`function areEqual(oldProps, newProps) { return oldProps.number === newProps.render; }

const MemoizedComponent = React.memo(myComponent, areEqual);`
__

React.lazy

A React function for dynamically importing components, creating a potential performance boost when certain components are included in a module but not necessary for the initial render. The lazy function takes in a callback function that is run when the component is used, and this function should return a call to the import function. For example:

const LazyComponent = react.lazy(() => import('./MyComponent'));
__

React.Suspense

A react component for specifying a fallback interface while a child component is preparing to render (such as waiting for a lazy import). The Suspense component takes a fallback prop of a React element, and its children prop is a suspending component. For example:

<React.Suspense fallback={<LoadingIndicator />}> <LazyComponent /> </React.Suspense>
__
__

Custom Hooks

A helper function that uses hooks. When hook code becomes redundant or too long to easily read, it can be helpful to move that code into a helper function. To denote that this helper function uses a hook itself, the name should be prefixed with use just like the built-in React hook functions.

__
__

Portals

A built-in method for rendering React elements into a DOM node outside of the parent React tree.

__

A portal is created by using the ReactDOM.createPortal function, which takes in a React element as the first parameter and the DOM node as the second parameter. The element will be appended to that DOM node, but it will still act the same as any other element in the original React tree (it can still take props, read from context providers and have events bubble up).

__
__

Class-Based Components

A JavaScript class that extends the React.Component class and acts as a React component.

__

All class-based components must implement a render method, which usually returns JSX similar to a functional component.

__

Instead of taking props as a parameter, all class-based components store their props in the this.props instance variable. Moreover, state is stored in this.state and updated using the this.setState method.

__

Class-based components cannot use hooks. Instead, they can implement a variety of lifecycle methods that work similar to hooks. These are some of the more common ones:

  • componentDidMount: Runs immediately after the component mounts. This method is usually used for setting up subscriptions.
  • componentDidUpdate: Runs immediately after the component updates due to a state or props change. A common use case for this method is for network requests that depend on props or state.
  • componentWillUnmount: Runs right before a component unmounts. This method is usually used for cleaning up any subscriptions.
  • shouldComponentUpdate: Similar to React.memo, determines if the component should re-render based on new props and new state values.
__
__

Error Handling

Error Boundary

A React component that catches errors in child components, preventing the entire application from crashing from a single error.

__

Error boundaries must be class-based components in order to take advantage of two lifecycle methods:

  • static getDerivedStateFromError(error): Called during the render phase and updates the current state of the component.
  • componentDidCatch(error, errorInfo): Called during the commit phase for the purpose of side-effects related to the caught error.

For example, this would be a complete error boundary component:

class ErrorBoundary extends Component { state = { hasError: false }; static getDerivedStateFromError(error) { return { hasError: true }; } componentDidCatch(error, errorInfo) { logErrorToServer(error, errorInfo); } render() { if (this.state.hasError) { return this.props.fallback; } return this.props.children; } }
__
__

Debugging React

React.StrictMode

A React component for putting a component in strict mode. Strict mode has two primary benefits for assisting in debugging:

  • It provides warnings when using deprecated functions or lifecycle methods.
  • It double-invokes some functions, such as functional components. This helps find potential bugs related to side-effects in functions that should not have side-effects.
__

React.Profiler

A React component for tracking how often a component renders. The Profiler requires two props:

  • id: A unique identifier.
  • onRender: A callback function to run after the component renders (during the commit phase).

For performance reasons, the Profiler is ignored in production mode.

__

React DevTools

An official React browser extension for debugging React.

__
__

Best Practices

DRY Component

Short for don't repeat your code, a principle involving refactoring any repeated code into helper functions. In React, we follow DRY principles by moving shared interfaces into helper components and common hook logic into custom hooks.

__
__

React Under the Hood

React Element

The internal object representation of a node in the React tree. React elements can represent either DOM nodes or React components.

__

Virtual DOM

A "virtual" representation of the DOM kept by React internally. Since this data structure is not tied to the actual DOM, it is much quicker to update than the DOM.

__

Reconciliation

The algorithm used by React to determine the "diff" between two trees of React elements. After each state update, React runs the reconciliation algorithm to determine what has changed, and that changelog is sent to the rendering function (in the case of the browser, this is from React DOM) which can update the page using the information.

__
__

Companion Libraries

Redux

A JavaScript state-management library often used with React. Redux uses reducer functions to create a global store that any component can read from.

__

Recoil

A JavaScript state-management library built for React. Recoil uses atoms, which are global pieces of state that any component can subscribe to.

__

Server-Side Rendering

A method of rendering an application where the server generates the final HTML page, rather than giving the client an empty HTML file and the scripts needed to generate the page. Server-side rendering can create significant performance improvements while also helping with search-engine optimization.

__

Static-Site Generation

Similar to server-side rendering, a method of rendering an application where the server generates the final HTML pages, rather than giving the client an empty HTML file and the scripts needed to generate the page. The key distinction between static-site generation and server-side rendering is that static-site generation creates all possible HTML files at build time, whereas server-side rendering creates a new HTML file for each server request.

__

Next.js

A JavaScript framework built around React. The primary use case for Next.js is server-side rendering, but it also includes a wide variety of other tools to simplify development and improve performance.

__

Gatsby

A JavaScript framework with the primary use case of static-site generation. In addition to static-site generation, Gatsby also includes a wide variety of other features that simplify development and improve performance, similar to Next.js.

__

React Router

A React library for declaratively controlling page routing from the client-side.