Built-in React Hooks
Hooks are a new addition in React 16.8. They let you use state and other React features without writing a class. Tey are build-in in the chore of React.
One of the benefits of React is that it does for you, if you determine some sort of system to manage the state of the application
Changing the state of the application and as you change the state of the application the webpage itself re-renders automatically to show the new values.
List of Hooks
State Hooks
To add state to a component, use one of these Hooks:
useStatedeclares a state variable that you can update directly.useReducerdeclares a state variable with the update logic inside a reducer function
useState
useState is a React Hook that lets you add a state variable to your component.
When data changes re-render de UI
An example of using useState
1 | // Reactive value, setter |
useReducer
It’s an alternative to the useState, which form me is less cleaner and adding extra complexity. I wouldn't use Redux is more complex rather than use setState to manage the state when it grows.
Declares a state variable with the update logic inside a reducer function.
Call useReducer at the top level of your component to manage its state with a reducer.
An example of using useReduce
1 | // Similar to set state, but a different way to set/manage state using the REDUX pattern. |
Effect Hooks
Effects let a component connect to and synchronize with external systems. This includes dealing with network, browser DOM, animations, widgets written using a different UI library, and other non-React code.
useEffectconnects a component to an external system.
Effects are an “escape hatch” from the React paradigm. Don’t use Effects to orchestrate the data flow of your application. If you’re not interacting with an external system, you might not need an Effect.
There are two rarely used variations of useEffect with differences in timing:
useLayoutEffectfires before the browser repaints the screen. You can measure layout here.- useInsertionEffect fires before React makes changes to the DOM. Libraries can insert dynamic CSS here.
useEffect
useEffect is a React Hook that lets you synchronize a component with an external system.
useEffect(setup, dependencies?)
An example of using useEffect
Call useEffect at the top level of your component to declare an Effect:
1 | import { useEffect } from 'react'; |
useLayoutEffect
Pitfall: useLayoutEffect can hurt performance. Prefer useEffect when possible
- Similar to useEffect but
- RUNS after render, but before pointing the script.
- CAUTION blocks visual updates until your callback is finished.
useLayoutEffect is a version of useEffect that fires before the browser repaints the screen.
useLayoutEffect(setup, dependencies?)
An example of using useLayoutEffect
Call useLayoutEffect perform the layout measurements before the browser repaints the screen:
1 | import React, { useState, useLayoutEffect, useRef } from 'react'; |
Note that useLayoutEffect should be used sparingly, as it can negatively impact the performance of your application if used excessively or inefficiently. You should only use useLayoutEffect when you need to perform a measurement or layout calculation that affects the visual appearance of your application.
Ref Hooks
Refs let a component hold some information that isn’t used for rendering, like a DOM node or a timeout ID. Unlike with state, updating a ref does not re-render your component. Refs are an “escape hatch” from the React paradigm. They are useful when you need to work with non-React systems, such as the built-in browser APIs.
- useRef declares a ref. You can hold any value in it, but most often it’s used to hold a DOM node.
- useImperativeHandle lets you customize the ref exposed by your component. This is rarely used.
Easiest way to manipulate and access DOM elements.
useRef
useRef is a React Hook that lets you reference a value that’s not needed for rendering.
const ref = useRef(initialValue)
An example of using useRef
Use the useRef hook in a React component to store a reference to a DOM element:
1 | import React, { useRef } from 'react'; |
By using the useRef hook to store a reference to the input element, we can avoid the need to rely on DOM queries or selectors to manipulate the input element, which can be slower and less reliable. Instead, we can directly access the input element using the current property of the inputRef object.
Creating a some short of to-do application, clear an input file when submitted the value
Context Hooks
Context lets a component receive information from distant parents without passing it as props. For example, your app’s top-level component can pass the current UI theme to all components below, no matter how deep.
- useContext reads and subscribes to a context.
useContext
To share value through disconnected components, we can create a context object.
useContext is a React Hook that lets you read and subscribe to context from your component.
const value = useContext(SomeContext)
Examples of using useContext
1 | import { createContext, useContext } from "react"; |
1 | const ThemeContext = React.createContext('light'); |
Performance Hooks
A common way to optimize re-rendering performance is to skip unnecessary work. For example, you can tell React to reuse a cached calculation or to skip a re-render if the data has not changed since the previous render.
To skip calculations and unnecessary re-rendering, use one of these Hooks:
- useMemo lets you cache the result of an expensive calculation.
- useCallback lets you cache a function definition before passing it down to an optimized component.
Sometimes, you can’t skip re-rendering because the screen actually needs to update. In that case, you can improve performance by separating blocking updates that must be synchronous (like typing into an input) from non-blocking updates which don’t need to block the user interface (like updating a chart).
To prioritize rendering, use one of these Hooks:
- useTransition lets you mark a state transition as non-blocking and allow other updates to interrupt it.
- useDeferredValue lets you defer updating a non-critical part of the UI and let other parts update first.
useMemo
useMemo is a React Hook that lets you cache the result of a calculation between re-renders.
- MEMOIZATION: cache result of function call, to optimize performance
- CAUTION: this only used as needed for expensive computations
An example of using useMemo
1 | // When data changes re-render de UI |
useCallback
useCallback is a React Hook that lets you cache a function definition between re-renders.
An example of useCallback
In this example, the ChildComponent receives the onClick prop from the ParentComponent and uses it to handle a click event on a button element. Because the onClick prop is a memoized callback function, the ChildComponent can safely use it without needing to worry about unnecessary re-renders due to changes in the function reference.
1 | // Maybe we want to memoize the function, passing the function to multiple child components, |
useDeferredValue
The useDeferredValue Hook is a new addition to React 18 and it lets you defer updating a part of the UI.
const deferredValue = useDeferredValue(value)
useDeferredValue allows you to defer the rendering of a value until a future point in time, which can be incredibly useful in situations where you want to avoid unnecessary rendering.
1 | const [valueToDefer, setValueToDefer] = useState("") |
By using the useDeferredValue Hook, you can avoid this problem by deferring the rendering of the search results until the user stops typing. This is similar to how debouncing works; it can dramatically improve performance.
The following example shows how to use the useDeferredValue Hook to simulate a debouncing pattern retrieving Star War’s characters names.
1 | import { useDeferredValue, useEffect, useState } from "react" |
In this example, it’s using the useState hook to manage the searchQuery state, which holds the user’s search input. We’re also using the useDeferredValue hook to create a deferredSearchQuery variable, which we pass to the Star Wars API search endpoint after a 1 second delay.
Other Hooks
These Hooks are mostly useful to library authors and aren’t commonly used in the application code.
- useDebugValue lets you customize the label React DevTools displays for your custom Hook.
- useId lets a component associate a unique ID with itself. Typically used with accessibility APIs.
- useSyncExternalStore lets a component subscribe to an external store.
useDebugValue
useDebugValue is a React Hook that lets you add a label to a custom Hook in React DevTools.
useDebugValue(value, format?)
An example of using useDebugValue
1 | // Use in multiple components. |