what and why

Hooks were introduced with React 16.8. Hooks allow you to use some React features (such as state) without writing classes.

Hooks are backwards-compatible.

Hooks are functions that let you ‘hook’ into React state and lifecycle features from function components. Hooks don’t work in classes, they allow you to use React without classes.

React has built-in hooks and you can also create your own!

Hooks are JavaScript functions! There are 2 rules:

  • They must be called at the top level. Don’t call Hooks inside loops, conditions or nested functions.
  • They must be called from React function components. Don’t call hooks from regular JavaScript functions.

Hooks solve a lot of problems. In React you cannot attach reusable behaviour to a component. Hooks allow you to share stateful logic. Hooks alllw you to extract stateful logic from a component, so that it can be tested independently and reused. Hooks allow you to reuse stateful logic , without changing the component hierarchy. This makes it easier to share Hooks among components.

Hooks let you split one component into smaller functions, based on which pieces are related, rather than forcing a split that is based on lifecycle methods.

Class components can encourage unintentional patterns that make optimisations fall back to a slower path. Classes don’t minfy well and therefore reduce chances for optimisation. Hooks let you use more React features without needing to use classes.

You don’t have to use Hooks! They will work with existing code. Currently classes are still supported.