DEV Community

Cover image for Understanding React hooks
Elizabeth
Elizabeth

Posted on • Edited on

Understanding React hooks

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.

Now that I understand it a little better, I've decided to write an article explaining hooks based on my understanding, and I am hoping to help someone else.

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, for programmers like me (who 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?
Well, 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. And when it comes to React hooks there are some rules you need to follow to use them. I've listed some of them below:

  • 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, It would be called 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'll 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'll 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 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 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'll be explaining the useEffect hook.

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.

Top comments (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

Thank you for reading

Some comments may only be visible to logged-in visitors. Sign in to view all comments.