What are hooks? What hooks do you know?

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 or useEffect — 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 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.

Do you accept cookies?

Cookies are small amounts of data saved locally on you device, which helps our website - it saves your settings like theme or language. It helps in adjusting ads and in traffic analysis. By using this site, you consent cookies usage.