Hooks

Essential React

Let's build a real app!

How can this be achieved?

What are Hooks?

Hooks are functions that let you "hook into" React state and lifecycle features.

Built-in Hooks

  • useState
  • useEffect
  • useContext
  • useReducer
  • use…

How to use Hooks

The Hook function is called in the render function.

Depending on the Hook, it may have parameters and may provide a return value to access the provided functionality.

Rules of Hooks

  • Only call Hooks at the top level (not inside loops, conditions, or nested functions)
  • Only call Hooks from React function components or custom Hooks

The eslint-plugin-react-hooks enforces these rules.

History of Hooks

Before Hooks were introduced in 2019, features like state management required the use of class components .

With Hooks these features can be used in function components and thereby makes the code simpler and better reusable .

How to handle component-level state

The useState Hook

                
            

The array destructuring makes it easy to use multiple states in a component.

How to handle input

The onChange prop is a function which is called when the input is changed.

Use event.target.value to access the value which was entered.

Exercise

  1. Allow the user to enter their name
  2. The entered name is displayed as a greeting next to the input field
  3. Display the input field on top of the list – routing will come later

Solution

SyntheticEvent

Event handlers like onChange receive an instance of SyntheticEvent .

This is a wrapper for the native events , ensuring a consistent API and functionality across browsers.

SyntheticEvent API

  • e.target.value
  • e.preventDefault()
  • e.nativeEvent
  • API for specific event type (e.g. e.keyCode )

SyntheticEvent API

Recap

We learned…

  • How to handle component-level state with useState
  • How to handle input
  • What Hooks are and how to use them
  • That events are wrapped by SyntheticEvent

Questions?