DEV Community

Cover image for Simplify with useState React Hook
Maasa Kono
Maasa Kono

Posted on

Simplify with useState React Hook

I've only just begun to learn React Hooks, and I am already excited about how this will transform my code to become cleaner and less bulky!

What are React Hooks?

Hooks are available as of React 16.8. It gives us the ability to build a React application using only functional components, wherein we can now use state without having to rely on a class component, and we can hook into React features.

This is pretty awesome, because it eliminates the need to worry about having to convert a functional component into a class component if you end up needing to use state in it.

React comes with several built-in Hooks, but you could also build our own. In this blog, I'm going to show you how I was able to utilize one of the built-in Hooks - useState.

useState

When creating a form, generally it starts out looking like this class component:

import React, { Component } from 'react';

class Form extends Component {
  state = {
    input: ''
  }

  handleOnChange = (event) => {
    this.setState({
      input: event.target.value
    })
  }

  render() {
    return (
      <div>
        <form>
          <label>
            Input Field: 
            <input type='text' input='input' />
          </label>
          <button type='submit'>Submit</button>
        </form>
      </div>
    )
  }
}
Enter fullscreen mode Exit fullscreen mode

All we're doing here is updating the component's state as the value of the input field changes. The exact same thing can be accomplished by converting this to a functional component and implementing the use of useState:

// First, let's change the import:
import React, { useState } from 'react';

// Convert the class component into a functional component:
const Form = () => {
  // Here we will change the way we access state:
  const [input, setInput] = useState('');

  // We can remove render() as this is a functional component that just needs to return JSX:
  return (
    <div>
      <form>
        <label>
          Input Field: 
          <input
            // Instead of declaring a separate function for updating the state, we can simply do that here:
            onChange={event => setInput(event.target.value)}
            type='text' 
            input='input' />
        </label>
        <button type='submit'>Submit</button>
      </form>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

So to explain what we've done here, we first needed to import the useState package so that we can use it in our code. You will also note that we are no longer importing Component.

Next we converted the class component into a functional component. Remember that we will no longer have access to the keyword this, so any instances of that will need to be removed.

Now, when it comes to actually using useState, here is the syntax:

const [input, setInput] = useState('');
Enter fullscreen mode Exit fullscreen mode

useState returns two values: 1) the current state and 2) the function that updates it (these variables can be named anything). When we call useState(), we pass in the initial state as an argument, which is why in this case it is an empty string.

Moving on, the next change was to remove render(). We have a functional component now, and all it does is return JSX.

Finally, inside the form we are calling the setInput function at the onChange event so that we can update the value of state. We could have kept the handleOnChange function and called setInput in there, but there wasn't a whole lot going on in there so I just went ahead and removed it.

And that's it! 'Works the same and it requires fewer lines of code.

Here is the awesome documentation for React Hooks!

Top comments (2)

Collapse
 
paras594 profile image
Paras 🧙‍♂ī¸

Nicely explained !!

Collapse
 
maasak profile image
Maasa Kono

Thank you! So happy to hear that. :)