Hooks are a mechanism in React that allows you to work without classes. It doesn't add anything new, but it simplifies code reuse to solve frequent problems.
Currently, this is the main way to write React applications. But hooks don't replace classes entirely. Moreover, the React team doesn't plan to remove support for classes. And you can do something without classes. An example of how the useState
hook works for storing the state:
// useState – built-in React hook
// To be discussed in more detail in the next lesson
import React, { useState } from 'react';
const Example = () => {
// It is the example of a hook for working with the state
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} time(s)</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
};
Hooks are functions with names usually beginning with use
so they are easy to distinguish. React has about ten hooks built in, only a few of which programmers use regularly. The main ones repeat the functionality of class components, such as working with state, side effects (lifecycle), context, and direct access to the Dom. We'll look at them throughout the course. You can find information on the remaining hooks in the official documentation.
In addition to the built-in ones, you can find hundreds, if not thousands, of ready-made hooks for all purposes on the web. For example, the popular react-use has more than 115 hooks. Now, development in React has turned into the search and use of suitable hooks. It is good because you can focus on your tasks and worry less about inventing bicycles.
Recommended materials
Are there any more questions? Ask them in the Discussion section.
The Hexlet support team or other students will answer you.
For full access to the course you need a professional subscription.
A professional subscription will give you full access to all Hexlet courses, projects and lifetime access to the theory of lessons learned. You can cancel your subscription at any time.