DEV Community

Charity Parks
Charity Parks

Posted on

React Hooks do what???

It took me a minute (a lot of minutes) to understand React Hooks. Here is a little bit of basic Hook info.

Prior to React Hooks being introduced, functional components were very limited in what they could do. With React 16.8 we were introduced to Hooks that provide a lot of flexibility to reuse code! It allows you to use state and other React features without writing a class. Hooks are the functions which "hook into" React state and lifecycle features from function components.

Hooks are Javascript functions but have additional rules. Don't call Hooks inside loops, conditions or nested functions. Only call Hooks at the top level AND only from React function components.

An example of a Hook we will see in a counter component that has a button to update the counter. Set an initial state the value of 0. We want the counter to increase by 1 each time the button is clicked. We will need an event handler for that. But to simply look at the useState Hook see below:

import { useState } from 'react';

function ThisExample() {
const [ count, setCount ] = useState(0);

useState returns 2 values: the current state and a function to update it.

Top comments (0)