DEV Community

loading...
Cover image for Understanding React hooks

Understanding React hooks

Elizabeth
I am a frontend developer, and I write react.js code these days. I am hoping to share my knowledge with others. she/her
Updated on ・4 min read

Hooks are now inevitable for React developers who use functional components. I struggled with the concepts of hooks when I started with reactjs, and I couldn't find an exact tutorial that would explain it well. So I'm writing this and hoping to help someone else, you know. Let's get in there right away.

What are hooks and why should I care?

So, during the early days of React, if a developer needs a state that will change later on. They will have to use a class component. But using classes in Javascript could be stressful for developers for a lot of reasons. So, in order for programmers like me (that still struggle with understanding classes in javascript) to keep using react the React team introduced hooks when they released React version 16.8. 0.

So what are hooks? according to the Reactjs team

They let you use state and other React features without writing a class.

Hooks lets you use some of the superpowers that react has without using a class.

Rules of using hooks

We all hate rules, don't we? But without rules, a lot of things will go wrong. I will list out some of the rules you need to follow to use hooks.

  • You can only use hooks in functional components, not classes or a regular javascript function.

  • You cannot use react hooks inside of conditional statements, loops, or nested functions.

  • Whenever you're creating a custom hook, you should always prefix it with "use". for example if I have a hook that checks the size of my window, I'd call that hook useWindowSize. We'll address this better when we're creating custom hooks.

To know more about the rules of hooks you can read the Rules of hooks page

Let's start using hooks

For the rest of this article, we'd be exploring the different hooks in react and how to create our very own hook.

useState

react state is one of the most popular reasons why hooks were created. A React state lets a component declare and manage data internally. useState makes the component re-render whenever you change the value in the state. Let's take a look at this example

import React, { useState } from 'react';


const CompName = () => {
 const [userName] = useState('Elizabeth');
 return (
   <div>
     Hello World! my name is {userName}
   </div>
 )
}
Enter fullscreen mode Exit fullscreen mode

In the code above we are using the state hook. As you can see I passed 'Elizabeth' to the hook. Also, you'd notice that the hook returns an array. The first index of the array will return the value that was passed to the hook (you can name it whatever you want). In our case, Elizabeth. The second index of the array returns a function that allows us to modify the state.

Let's modify our example above to display whatever is being passed to a form.

Show some magic
import React, { useState } from 'react';


const ShowHide = () => {
  const [show, setShow] = useState(false);
  return (
    <div>
     <button onClick={() => setShow(!show)}>{show ? 'Show me 
      some magic' : 'Hide the magic'}</button>
       {show && (<p>Some magic</p>)}
     </div>
   )
 }
Enter fullscreen mode Exit fullscreen mode

In the code above, we're using the state to show and hide some magic😁 Here's the output of the code.

Using arrays and objects

The state hook can also accept arrays and objects. However, setting an object state is quite different from setting a string state. Imagine you have an object with different properties and you want to update the value of one property in that object, the example below wouldn't be the right way to update your state.

  const [person, setPerson] = useState({name: 'Tolulope', age: '34'});
  setPerson({name: 'Tofa'});

console.log(person);
// expected result: name: 'Tofa'
Enter fullscreen mode Exit fullscreen mode

if you click on the update name button above you'd see that the age disappears. This is because the new object passed into setPerson overrides what was previously in the object.

The setState accepts a parameter that contains the previous state. So in order to set an object state using our previous code, you spread the previous state and then pass the property you would like to update like the example below

setState((prevState) => 
 {
  ...prevState,
  name: 'Tofa'
 })
Enter fullscreen mode Exit fullscreen mode

The example above will first of all copy what was in the previous state, then update the name property to "Tofa".

UseState and functions

useState also accepts functions, for example, if you have a case where you have to do some complex calculation in order to set your state, you'll want it to run just once you pass a function to the useState. Passing a function to your useState will only make that function run once, which is once the component mounts.

Conclusion

You can do more with states so I'd advise you to try exploring the possibilities.

In my next post, I'd be talking about another hook called useEffect.
If you enjoyed this post please like and share. If you have questions please feel free to drop them in the comments section. In the main time. Keep coding and doing amazing things.

Discussion (5)

Collapse
727021 profile image
Andrew Schimelpfening

This is a great basic overview of react hooks. Thanks for sharing!

Collapse
bc profile image
Brian Canzanella

thanks for sharing this!

Collapse
ilizette profile image
Elizabeth Author

Thank you for reading

Collapse
nnn_aaa_2201debcb86c84b03 profile image
nnn aaa

This is great, have been reading the whole series (but not in order)

I did notice in the 4th sentence of your section titled "What are hooks and why should I care?" you say, "So, in other for..." I am guessing that is a typo and you mean to say "So, in order for..."

Collapse
ilizette profile image
Elizabeth Author

Thank you so much for reading and thanks for pointing that out. It is indeed an error. I'd correct that. Thank you so much