Custom Hooks In React

Custom Hooks makes it really easy to share stateful logic amongst the components. This makes the react components even more composable.

Syntax Summary

  • Take the hook out of the main code & put in a function.

  • Return the state variable you need in your render/view

So let's discuss one example of useInput Custom Hook

Code Snippet as below:

import { useState } from "react";

const useInput = (defaultVal) => {
  const [val, setVal] = useState(defaultVal);

  const updateValue = (e) => {
    setVal(e.target.value);
  };

  return [val, updateValue];
};

export default useInput;

So we extracted the value of the input field & put that into a separate function that is nothing but useInput() as Custom Hook.We can use the above hook as below:

import React, { useState } from "react";
import useInputState from "./customHook/useInput";
import "./styles.css";

export default function App() {
  const [password, setPassword] = useInput();
  const [msg, setMsg] = useState();

  const formSubmitHandler = (e) => {
    e.preventDefault();
    const isAlphaNumericRegex = /\d/;
    if (isAlphaNumericRegex.test(password)) {
      setMsg("Pasword is very strong");
    } else {
      setMsg("Password is weak");
    }
  };
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <form onSubmit={formSubmitHandler}>
        <input onChange={setPassword} />
        <button type="submit">Submit</button>
        <br />
        <br />
        {msg}
      </form>
    </div>
  );
}

Conclusion: Simple we put a stateful logic into a separate function.