Crystallize

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 the use of class constructors. Let us see how we can use this is a very simple way.

React Hook example

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

yarn add react@next react-dom@next

Lets 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 going on 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 Hooks is a proposal that could change how we manage state in simple components. It will be interesting to see how Hooks look like when it lands, and how big of an impact it will have on the React landscape.