In this section, we will talk about such an extremely important element of the application at the present time as the state. React gives us the ability to work with the state of a component. A child component can learn about a change in the parent's state via
props. But what if the components do not have a common ancestor? The application constantly receives and sends data to the server, how many components can know about it? Is it possible to store application data in some centralized repository so that the desired components can access it? These and many similar questions are not unfounded. They require serious consideration, as they inevitably arise as the application grows.
Hooks are new in React 16.8 that allow you to use state and other React features without writing classes. These are functions with which you can hook into React state and lifecycle methods from functional components.
Hooks don't work inside classes - they give you the ability to use React without classes.
The first hook we'll look at is the
In this example,
useState is a hook. We call it to endow our functional component with internal state. React will keep this state between renders. The call to
useState returns an array with two elements, which contains: the current value of the state (getter) and a function to update it (setter). This function can be used anywhere, for example, in an event handler.
The only argument to useState is the initial state. In the example above, this is
0, since our counter starts at zero. The original argument value is used only on the first render.
Thanks goes to these wonderful people (emoji key):