Hooks in React enable usage of React state and lifecycle features without using a class. Released in React v16.8.0, Hooks resolve issues like sharing stateful logic across components.
Rather than writing higher-order components, a customized hook can be implemented outside of a component in order to reuse that logic and test it in isolation. This also means the components themselves become simpler to manage by breaking it into smaller pieces of state related functions.
Functional components have many benefits over using classes. The top-down approach in functional components means it's easier to read and comprehend. In a class, binding this
can be difficult to keep track of and introduces potential for bugs. In addition, without classes there is no need to wire up the component lifecycle functions and write potentially complicated logic to identify changes in props or state.
The useState
hook will add local state to a functional component. This function returns an array pair, one being a variable for the current state value and another for a function to update the state value.
For more information about the State Hook, check out the React Docs.
In a class, the lifecycle functions of componentDidMount
, componentDidUpdate
and componentWillUnmount
can help fetch data or manipulate the DOM. Without the ability to do this inside a functional component React forced using a class to take advantage of these features. With the useEffect
hook, these features can be mimicked without the need for a class component.
React will run the provided callback function after the DOM has updated on every render.
For more info, see the React Docs
In addition to the blog post, Dan Abramov had a great talk about React Hooks at React Conf 2018.