Components and Hooks

Components and Hooks

building blocks in React:

  • components: handle the ui / view
  • hooks: handle the model / logic behind the view

Hooks

Hook = special function that can be called inside a component definition

possible examples:

  • useState
  • useEffect: for triggering side effects (e.g. API queries)
  • useQuery: more convenient way to query APIs
  • useTodos: custom hook for managing an array of todos

Rules of Hooks

inside a component defintion:
hooks must be called in the same order on every render

(React uses call order to keep track of hook identity)

Rules of Hooks on reactjs.org

External components and hooks

External components and hooks

some components and hooks from libraries:

  • MUI (Material-UI): <Button>, <Alert>, ...
  • React Router: <Route>, <Link>, useParams, useNavigate
  • react-query: useQuery
  • react-hook-form: useForm
  • React built-ins: <Suspense>, useEffect, useContext, ...

External components and hooks

lists of available components and hooks:

awesome-react-components: list of components, ...

awesome-react-hooks: list of hooks

Custom components and hooks

Custom components and hooks

use cases:

  • structuring code
  • reusing code / functionality

Custom components and hooks

example components for reuse (within a project or across projects):

  • Button (for styling)
  • Calendar
  • ProgressBar

Custom components and hooks

example components for structuring code:

  • TodoApp
  • TodoList
  • TodoItem

Custom components and hooks

examples of custom hooks:

in a todo app: useTodos

in a web shop app: useProducts, useCart

Example: Todo list application

using custom components and a custom hook for a todo list application:

function TodoApp() {
  const todoData = useTodos();
  return (
    <div>
      <Header />
      <AddTodo onAdd={todoData.addTodo} />
      <TodoList
        todos={todoData.todos}
        onDelete={todoData.deleteTodo}
        onCompletedChange={todoData.setCompleted}
      />
      <Statistics todos={todoData.todos} />
    </div>
  );
}