Lesson 02-React Functional Components and Hooks

Differences Between Functional and Class Components

React offers two primary ways to define components: functional components and class components. With the introduction of React Hooks, functional components have become more powerful, and many developers prefer them over class components.

Syntax and Structure

Functional Components:

  • Simple to define, typically consisting of a function that returns JSX.
  • No instantiation required, no this keyword.
  • Leverage React Hooks for state and side-effect management.
import React from 'react';

function FunctionComponent(props) {
  const [state, setState] = React.useState(0);

  return (
    <div>
      <p>You clicked {state} times</p>
      <button onClick={() => setState(state + 1)}>
        Click me
      </button>
    </div>
  );
}

Class Components:

  • Require extending React.Component.
  • Use this.state and this.setState() for state management.
  • Require binding event handlers to this.
import React, { Component } from 'react';

class ClassComponent extends Component {
  constructor(props) {
    super(props);
    this.state = { count: 0 };
  }

  handleClick = () => {
    this.setState({ count: this.state.count + 1 });
  };

  render() {
    return (
      <div>
        <p>You clicked {this.state.count} times</p>
        <button onClick={this.handleClick}>
          Click me
        </button>
      </div>
    );
  }
}

State Management and Lifecycle

Functional Components:

  • Use useState for state management.
  • Use useEffect for side effects, such as subscribing to data streams or cleanup on unmount.
  • Use useContext to consume context.
  • Use useReducer and useCallback for performance optimization and complex state management.

Class Components:

  • Use state and setState for state management.
  • Offer extensive lifecycle methods like componentDidMount, componentDidUpdate, and componentWillUnmount.
  • Use getDerivedStateFromProps and shouldComponentUpdate to control updates.

Performance and Readability

Functional Components:

  • More concise, easier to understand and maintain.
  • Hooks make state and side-effect management intuitive.
  • Can use memoization (e.g., React.memo, useMemo) for performance optimization.

Class Components:

  • May include more boilerplate code.
  • Lifecycle methods can scatter logic, making it harder to track.
  • Often require manual optimization, such as using PureComponent or shouldComponentUpdate.

Functional Components:

  • With React 18, functional components and Hooks are the recommended approach.
  • Supported by more libraries and frameworks in the community.

Class Components

  • Still widely used in legacy projects.
  • Supported long-term, but less common in new projects.

Hooks

use()

The use() hook reads values from resources like Promises or context.

import { use } from 'react';

function MessageComponent({ messagePromise }) {
  const message = use(messagePromise);
  const theme = use(ThemeContext);
  // ...
}

function HorizontalRule({ show }) {
  if (show) {
    const theme = use(ThemeContext);
    return <hr className={theme} />;
  }
  return false;
}

useState()

  • State Variable: Retains data between renders.
  • State Setter Function: Updates the variable and triggers a re-render.
import { useState } from 'react';

function MyComponent() {
  const [age, setAge] = useState(28);
  const [name, setName] = useState('Taylor');
  const [todos, setTodos] = useState(() => createTodos());
  // ...
}

useCallback()

The useCallback() hook returns a memoized function, preventing re-renders. When passed to a child component, it avoids unnecessary re-renders during parent updates.

// fn: The function to memoize. It can take any arguments and return any value.
// dependencies: A list of all reactive values referenced in fn, including props, state, and variables/functions declared in the component.
const cachedFn = useCallback(fn, dependencies);

import { useCallback } from 'react';

export default function ProductPage({ productId, referrer, theme }) {
  const handleSubmit = useCallback((orderDetails) => {
    post('/product/' + productId + '/buy', {
      referrer,
      orderDetails,
    });
  }, [productId, referrer]);
}

useReducer()

The useReducer() hook consolidates state update logic into a reducer function outside the component.

Steps to use useReducer:

  1. Move from setting state to dispatching actions.
  2. Write a reducer function.
  3. Use the reducer in your component.
  • Reducers must be pure: They run during rendering and must produce the same output for the same input. Avoid side effects like requests or timeouts.
  • Each action describes a single user interaction: For example, dispatching a reset_form action is clearer than multiple set_field actions. Actions should be logged clearly for debugging.
const [state, dispatch] = useReducer(reducer, initialArg, init?);

import { useReducer } from 'react';

function reducer(state, action) {
  // ...
}

function MyComponent() {
  const [state, dispatch] = useReducer(reducer, { age: 42 });
  // ...
}

function handleClick() {
  dispatch({ type: 'incremented_age' });
  // ...
}

useContext()

Basic usage of useContext:

  1. Create a context object with createContext.
  2. Use useContext to access the context value.
  3. Wrap the root component with <Context.Provider>.
import { useContext, createContext } from 'react';

export default function Section({ children }) {
  const LevelContext = createContext(0);
  const level = useContext(LevelContext);
  return (
    <section className="section">
      <LevelContext.Provider value={level + 1}>
        {children}
      </LevelContext.Provider>
    </section>
  );
}

useContext() Summary:

  • Context allows a component to provide information to its entire subtree.
  • Passing Context:
  1. Create and export with export const MyContext = createContext(defaultValue).
  2. Read it with useContext(MyContext) in any child component, regardless of depth.
  3. Wrap children in <MyContext.Provider value={...}> at the root component.
  • Context passes through intermediate components.
  • Context enables components to adapt to their environment.
  • Before using context, try passing props or JSX as children.

useEffect()

The useEffect() hook defines a function and a dependency array. The function runs on component mount or when dependencies change, and the return function runs before component unmount. The dependency array specifies values that trigger the effect.

useEffect(() => {
  // Equivalent to componentDidMount, componentDidUpdate
  console.log("code");
  return () => {
    // Equivalent to componentWillUnmount
    console.log("code");
  };
}, [/*dependencies*/]);
  • No dependencies: useEffect runs after every render (like componentDidMount and componentDidUpdate).
  • Dependency array: useEffect runs only when listed dependencies change. An empty array runs the effect once on mount.

useMemo()

The useMemo() hook returns a memoized value, caching computation results between renders to avoid expensive calculations.

// calculateValue: Function to compute the cached value.
// dependencies: List of all reactive values referenced in calculateValue, including props, state, and variables/functions declared in the component.
useMemo(calculateValue, dependencies);

import { useMemo } from 'react';

function TodoList({ todos, tab }) {
  const visibleTodos = useMemo(
    () => filterTodos(todos, tab),
    [todos, tab]
  );
  // ...
}

useRef()

The useRef() hook retrieves a referenced object’s value at any time, accepting an initial value. Update the reference object’s value via ref.current.

ref can be used as an HTML attribute to assign a referenced object to a DOM element.

const ref = useRef(initialValue);

import { useRef } from 'react';

function MyComponent() {
  const intervalRef = useRef(0);
  const inputRef = useRef(null);

  intervalRef.current = intervalRef.current + 1;

  clearInterval(intervalRef.current);
  intervalRef.current = setInterval(() => {
    setNow(Date.now());
  }, 10);
}

const MyComponent = () => {
  const elementRef = useRef();
  return (
    <input ref={elementRef} type="text" />
  );
};

useDebugValue()

The useDebugValue() hook adds a label to custom hooks in React DevTools.

import { useDebugValue } from 'react';

function useOnlineStatus() {
  const isOnline = useSyncExternalStore(subscribe, () => navigator.onLine, () => true);
  useDebugValue(isOnline ? 'Online' : 'Offline');
  return isOnline;
}

useDeferredValue()

The useDeferredValue() hook defers updating part of the UI.

// value: The value to defer. Can be any type.
useDeferredValue(value);

import { Suspense, useState, useDeferredValue } from 'react';
import SearchResults from './SearchResults.js';

// query updates immediately, but deferredQuery retains its previous value until data loads, so SearchResults shows old results.
export default function App() {
  const [query, setQuery] = useState('');
  const deferredQuery = useDeferredValue(query);
  return (
    <>
      <label>
        Search albums:
        <input value={query} onChange={e => setQuery(e.target.value)} />
      </label>
      <Suspense fallback={<h2>Loading...</h2>}>
        <SearchResults query={deferredQuery} />
      </Suspense>
    </>
  );
}

useId()

The useId() hook generates a unique ID for accessibility attributes, similar to a UUID.

import { useId } from 'react';

function PasswordField() {
  const passwordHintId = useId();
  // ...
}

useImperativeHandle()

The useImperativeHandle() hook customizes the handle exposed as a ref.

useImperativeHandle(ref, createHandle, dependencies);
// ref: The ref received as the second argument of forwardRef.
// createHandle: A function that returns the exposed ref handle, which can be any type (typically an object with methods).
// dependencies: Optional list of reactive values referenced in createHandle.

import { forwardRef, useImperativeHandle } from 'react';

const MyInput = forwardRef(function MyInput(props, ref) {
  useImperativeHandle(ref, () => {
    return {
      // ... your methods ...
    };
  }, []);
});

useInsertionEffect()

The useInsertionEffect() hook inserts elements into the DOM before any layout effects.

// setup: Function containing side-effect logic.
// dependencies: Optional list of reactive values referenced in setup.
useInsertionEffect(setup, dependencies);

import { useInsertionEffect } from 'react';

// Inside your CSS-in-JS library
function useCSS(rule) {
  useInsertionEffect(() => {
    // ... inject <style> tags here ...
  });
  return rule;
}

useLayoutEffect()

The useLayoutEffect() hook is a version of useEffect that runs before the browser repaints the screen.

// setup: Function containing side-effect logic. Can return a cleanup function.
// dependencies: Optional list of reactive values referenced in setup.
useLayoutEffect(setup, dependencies);

import { useState, useRef, useLayoutEffect } from 'react';

function Tooltip() {
  const ref = useRef(null);
  const [tooltipHeight, setTooltipHeight] = useState(0);

  useLayoutEffect(() => {
    const { height } = ref.current.getBoundingClientRect();
    setTooltipHeight(height);
  }, []);
  // ...
}

useOptimistic()

The useOptimistic() hook enables faster UI updates.

// state: The initial value or value when no pending operations exist.
// updateFn(currentState, optimisticValue): A function that takes the current state and optimistic value and returns the optimistic state.
const [optimisticState, addOptimistic] = useOptimistic(state, updateFn);

import { useOptimistic } from 'react';

function AppContainer() {
  const [optimisticState, addOptimistic] = useOptimistic(
    state,
    (currentState, optimisticValue) => {
      // Merge and return new state with optimistic value
    }
  );
}

useSyncExternalStore()

The useSyncExternalStore() hook synchronizes with an external store.

// subscribe: A function that subscribes a callback to the store, calling it on changes to trigger re-renders. Returns a cleanup function.
// getSnapshot: A function returning a snapshot of the store’s data. Must return the same value if the store is unchanged.
// getServerSnapshot: Optional function returning the initial store snapshot for server rendering and hydration.
useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);

import { useSyncExternalStore } from 'react';
import { todosStore } from './todoStore.js';

function TodosApp() {
  const todos = useSyncExternalStore(todosStore.subscribe, todosStore.getSnapshot);
  // ...
}

useTransition()

The useTransition() hook updates state without blocking the UI.

const [isPending, startTransition] = useTransition();

import { useTransition } from 'react';

function TabContainer() {
  const [isPending, startTransition] = useTransition();
  // ...
}

API

cache

The cache API caches data fetching or computation results.

import { cache } from 'react';
import calculateMetrics from 'lib/metrics';

const getMetrics = cache(calculateMetrics);

function Chart({ data }) {
  const report = getMetrics(data);
  // ...
}

createContext

The createContext API creates a context that components can provide or read.

  • SomeContext.Provider: Provides a context value to components.
  • SomeContext.Consumer: A less common way to read context values.
import { createContext, useState } from 'react';
const ThemeContext = createContext('light');

function App() {
  const [theme, setTheme] = useState('light');
  // ...
  return (
    <ThemeContext.Provider value={theme}>
      <Page />
    </ThemeContext.Provider>
  );
}

forwardRef

The forwardRef API allows a component to expose a DOM node to a parent via a ref.

const SomeComponent = forwardRef(render);

import { forwardRef } from 'react';

const MyInput = forwardRef(function MyInput(props, ref) {
  // ...
});

lazy

The lazy API defers loading a component’s code until its first render.

const SomeComponent = lazy(load);

import { lazy } from 'react';
const MarkdownPreview = lazy(() => import('./MarkdownPreview.js'));

memo

The memo API skips re-rendering a component if its props are unchanged.

const MemoizedComponent = memo(SomeComponent, arePropsEqual);

const Greeting = memo(function Greeting({ name }) {
  return <h1>Hello, {name}!</h1>;
});

export default Greeting;

startTransition

The startTransition API updates state without blocking the UI.

startTransition(scope);

import { startTransition } from 'react';

function TabContainer() {
  const [tab, setTab] = useState('about');

  function selectTab(nextTab) {
    startTransition(() => {
      setTab(nextTab);
    });
  }
  // ...
}
Share your love