Custom hooks typescript

Barhoumi Khaled
React hooks Typescript & javascript
2 min readJan 13, 2021

To create react app with typescript open your terminal and change directory where is your project, than run one of this command:

npm create-react-app my-app --template typescript or

yarn create react-app your-app --template typescript

For whome like to see all the code first I just create a sandbox write here.

In this sample I will use material-ui, you only need to install this library

yarn add @material-ui/core

Now will create first our form: SingIn.tsx Please notethat the react functional name should start by uppercase not lowercase.

the file structure it’s gonna be like this:

Once we done with the form, Now we need to bind it with a model, let’s create a model and call it User.

Now will go ahead and create our custom hooks.

A custom Hooks are a new addition in React 16.8. They let you use state and other React features without writing a class. Hooks are backwards-compatible. With this we don’t actually need to use redux.

To do so we need to look what we need on our form. We need user model to bind the value for each textfield, the change event when one textfield change, and one more method to the submit button.

by convention the naming of the function start by handleAction, the same the naming convention for our custom hook its should start by use so we will name it by useSignIn.ts

We almost there!

no we need to bind the function method and the user model with our form to do we need to import the custom hook in the Singin.tsx

here is the final version of this form, we bind the value of login by user.login, and password by user.password. And we add the event change and bind it with handleInputChange we can name it too handleUserChange.

To see this form just import it to the App.tsx

import React from “react”;import “./styles.css”;import SignIn from “./form/SignIn”;export default function App() {  return (     <div className=”App”>       <h1>Custom hook</h1>       <SignIn />     </div>  );}

--

--