Skip to main content
🍞
Dev Corner
Simple Example of React Hooks

Simple Example of React Hooks

Hooks (added to React in version 16.8) allow function components to access state and other React features.

Simple Example of React Hooks

React Hooks Proposal

React Hooks was recently announced by Dan Abramov at React Conf, and it offers a new way to do really simple state management without using class constructors. Let us see how we can use this in a very simple way.

React Hook Example

To use hooks, you currently need to install the next version of React. Like so:

yarn add react@next react-dom@next

Let’s take the good old form setup. Look at this beauty:

import React from "react";

export default () => (
  <div className="App">
    <h1>React Hooks example</h1>
    <form action="https://example.com">
      <div>
        <label for="username">Username</label>
        <input name="username" id="username" />
      </div>
      <div>
        <label for="password">Password</label>
        <input name="password" id="password" type="password" />
      </div>
      <div>
        <button type="submit">Log in</button>
      </div>
    </form>
  </div>
);

There is no state; only pure HTML form action is happening here. What if you wanted to give some feedback to the user that the form has been submitted? Using react hooks, this is as simple as adding a couple of lines:

import React, { useState } from "react";

export default () => {
  const [posting, setPosting] = useState(false);

  return (
    <div className="App">
      <h1>React Hooks example</h1>
      <form action="https://example.com" onSubmit={() => setPosting(true)}>
        <div>
          <label for="username">Username</label>
          <input name="username" id="username" />
        </div>
        <div>
          <label for="password">Password</label>
          <input name="password" id="password" type="password" />
        </div>
        <div>
          <button type="submit">{posting ? "Logging in..." : "Log in"}</button>
        </div>
      </form>
    </div>
  );
};

That is all it takes! Just import useState from React and use it directly inside your component function. See here for details on how React hooks are planned to work.

Conclusion

React Hook is a proposal that could change how we manage the state in simple components. It will be interesting to see what Hooks looks like when it lands and how big of an impact it will have on the React landscape.