Hooks are nothing more than functions. They do not have a particular syntax; instead, they are the result of a certain agreement, an assumption that has been adopted.
Rules for writing and using hooks:
use
, for example, useState
or useEffect
— this helps recognize a hook.if
clauses, loops, or closures—this ensures that hooks always execute in the same order within the component during its re-rendering.Examples of built-in React hooks:
useState
- maintains the component's state.useEffect
- performs operations in each component re-render, based on the dependency array
. It replaces several functions known from class components, such as componentDidMount
or componentDidUpdate
. This hook can be used multiple times within a single component, and their execution order follows the same sequence as the order of declarations. For each useEffect
function, a callback
, or precisely an effect
, is passed. This callback
can return another function, called a cleanup function, which is always executed before the next execution of the effect itself—such as for cleaning up after the previous one.useRef
- acts as a container for data, changing which does not cause the component to re-render. Values can be assigned to the reference or used to point to a specific component by declaring the component as forwardRef
and passing the reference to it in the 'ref' property.useMemo
, useCallback
- hooks useful in memoization, i.e., storing values or entire functions between component re-renders. Useful when avoiding computations on every render—only changing values passed to the dependency array
will recalculate the values of these functions in the next re-render.You can find more information about hooks here.