React

React Logo

React Basics: Custom Hooks

App.js with the following:

  • Import the useForm.js file (see below)
  • Passing generically named getter/setter values (we're using "values" and "handleChange" instead of something like "myvalue" and "setMyvalue") representing JS objects instead of specifically named elements
  • Reference the specific values in object notation where needed (values.email and values.password)

App.js

import './App.css';
import React, {useState} from 'react';
import { useForm } from './useForm';

function App() {

  const [values, handleChange] = 
  useForm({email: '', password: ''});

  return (
    <div className="App">
      <header className="App-header">
        Email: 
        <input name='email' value={values.email} 
        onChange={handleChange} /><br/><br/>
        Password: 
        <input name='password' type='password' 
        value={values.password} 
        onChange={handleChange} />
      </header>
    </div>
  );
}

export default App;


useForm.js - Custom Hook

  • Set state values generically
  • Use the spread operator to use existing values in state....
  • ... then generically set the name/value pair of the submitted form values [e.target.name]: e.target.value
import React, {useState} from 'react';

export const useForm = (initialValues) => {
    const [values, setValues] = 
    useState(initialValues);

    return [
        values, 
        e => {
            setValues({
                ...values,
                [e.target.name]: e.target.value
            });
        }
    ]
}

export default useForm;