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:
- Their name should start with
use
, for example,useState
oruseEffect
— this helps recognize a hook. - Hooks can only be called in a functional component or another hook—this stems from their usage, such as in component re-rendering.
- Hooks should be called at the top level, directly within the component, as high as possible. They shouldn't be called inside
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 thedependency array
. It replaces several functions known from class components, such ascomponentDidMount
orcomponentDidUpdate
. 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 eachuseEffect
function, acallback
, or precisely aneffect
, is passed. Thiscallback
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 asforwardRef
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 thedependency array
will recalculate the values of these functions in the next re-render.
You can find more information about hooks here.