DEV Community

Cover image for Learning React: Hooks
Sarah Thompson
Sarah Thompson

Posted on

Learning React: Hooks

I'm taking you on a journey to learn React with me. It is the cool new framework, and I want to figure out exactly what all makes it so cool. And one of the places we are stopping to appreciate on the way are Hooks.

Hooks enabled us to use functional components instead of class-based components while dealing with the state. In fact hooks allow us to write components using just functions.

React has a topdown uni-directional data flow architecture that lets us break features of the UI into small reusable parts. But sometimes it is difficult to fully breakdown complex feature sets because the logic being used is stateful so it can't really be extracted to another method. Hooks allow us to be able to really organize the logic inside a complex component into reusable isolated units so that it is more readable and maintainable.

There are built in hook options, as well as the ability to write our own custom hooks. You shouldn't call hooks inside of loops, conditions, or nested functions instead they should be called at the top of a function.

These built in hooks can be imported from the same place React is imported from at the top of the file you are using them in.

import React, { useState, useEffect, useRef, useMemo } from 'react';
Enter fullscreen mode Exit fullscreen mode

One built in hook is useState which creates a pair of information. It gives us local state variable that we can name like "ThingBeingSet" and also useState provides for us a setter function to update the state that it creates. The setter function can be named anything, but typically it should be named with the syntax "setThingBeingSet".

We have the initial band state variable being set as an argument in useState to the band "Jukebox the Ghost". You don't need to set an argument in useState unless you want to in your code. That band variable then gets updated when the setter function is clicked in the button HTML element.

  const [band, setBand] = useState('Jukebox the Ghost');

  return(
<div>
   <button onClick={() => setBand("Frankie and the Witch Fingers")}>
        Change Band
    </button>
    <div>I am listening to {band}</div>
</div>
)
Enter fullscreen mode Exit fullscreen mode

Another built in hook is the Effect Hook, useEffect, which adds the ability to perform side effects from a function component. Side effects are when we interact with something external to the codebase itself like if we were fetching data from an API and it is something can alter a component's state in an unpredictable manner. This hook can act also like componentDidMount, componentWillUnmount, or the componentDidUpdate methods in react.

In the below function we are updating the page's title in the tab based on the quantity of clicks there have been.

useEffect(() => {
    document.title = `Button Clicked ${count} times`;
  });
Enter fullscreen mode Exit fullscreen mode

At the tail end of the useEffect hook you can add an array that is either empty, which means useEffect will only run once when the component loads, or full of state variables. If it is full of state variables the useEffect will be rerun every-time one of those variables change. Basically this means that you can set if the methods in useEffect happen when there are component changes in the DOM and which changes those should be.

useEffect(() => {
    fetch(SOMEAPI).then(
      ...
    )
  },[]);
Enter fullscreen mode Exit fullscreen mode

Hypothetically, adopting Hooks can reduce the bundle size of your application because code that uses hooks tend to minify more easily than the same code that is using classes. Hooks were added in React 16.8.

Discussion (3)

Collapse
sunflower profile image
sunflowerseed • Edited

the other person was saying... do you use 3 backticks on a single line to denote start and end of code? If you do, use the 3 backticks and then add js to the end of it, to mark the beginning of code, so that it will syntax highlight for JavaScript ... the end of code can just be 3 backticks

ah... or do you use four spaces in front of line to denote it is code? Doing so, it is not as easy as using 3 backticks and js to denote JavaScript... I think another method needs to be use, such as some kind of comments.

See dev.to/sunflower/the-only-two-valu... for the syntax highlighting of JS.

Collapse
anguramshan profile image
Anguram Shan

uesfull post๐Ÿ‘๐Ÿ‘

Also mention some advanced hooks. It'll be usefull for beginners ๐Ÿ‘

Collapse
salothom profile image
Sarah Thompson Author

That's a good point! Thanks!