At React Conf 2018, Hooks was introduced by Sophie Alpert and Dan Abramov, followed by Ryan Florence demonstrating how to refactor an application to use them. While giving his presentation, Ryan stated that hooks are the vision for the future.
According to React, “Hooks are a new addition in React 16.8. They let you use state and other React features without writing a class.” To explain this further, hooks are a backwards-compatible function that allows you to ‘hook into’ react state and lifecycle from a function component without having to depend on
There are three different types of hooks. We discuss these below:
useState is the simplest Hook that you can use. It does exactly what you would expect from its name. All you have to do is declare a variable (state) and a function, that is also called setter and this sets the value of that variable.
Sometimes, while coding, you may want to store a value for future reference in your component, but without triggering a re-render. This is a situation where useRef is used. It allows you to store a variable in the scope of the function, while still preserving its value across the renders. useRef receives an initial value and returns the ref variable.
In fact, useRef is a special case of useState. However, it allows you to set its value directly instead of using a setter function, which persists the value across renders without triggering a re-render.
The useEffecthook may be tricky for you to understand if you think too much of it in terms of the old React class lifecycles. Although its subtleties are not immediate, they do make sense.
For example, if you have a component that fetches data in the form of a list by hitting an API, you would want the component to hit the API and fetch the data list once the component is rendered (mounted).
What are the benefits of Hooks?
Below, we list out several benefits of using React Hooks:
- No rewrites to include or exclude state, just adding/deleting lines
- No need to memorize lifecycle methods with useEffects
- Customizable and reusable across components unlike class component state
- Much cleaner code
- No breaking changes
Put simply, React Hooks allows you to “hook into” React specific functionality such as its state and lifecycles, while also letting you keep your functional components as functions. It is not difficult to understand why it has so much potential.