0
//use Input HOOK

I want to know that how this custom hook work

import { useState } from "react";

export default initialValue => {
  const [value, setValue] = useState(initialValue);
  return {
    value,
    onChange: event => {
      setValue(event.target.value);
    },
    reset: () => setValue("")
  };
};


//todo form

How this onchange method work how it update the data even though no onchange function is write in this programm

import React from "react";
import TextField from "@material-ui/core/TextField";
import useInputState from "./useInputState";

const TodoForm = ({ saveTodo }) => {
  const { value, reset, onChange } = useInputState("");

  return (
    <form
      onSubmit={event => {
        event.preventDefault();
        saveTodo(value);
        reset();
      }}
    >
      <TextField
        variant="outlined"
        placeholder="Add todo"
        margin="normal"
        value={value}
        onChange={onChange}
      />
    </form>
  );
};

export default TodoForm;

view full programm Code Sandbox link

Scott Marcus
  • 64,069
  • 6
  • 49
  • 71
  • It's not clear what you're asking. This hook basically moves some of the standard boilerplate you'd otherwise typically write for form inputs into a single function (the custom hook you quote). It returns some props/attributes, including the `onChange` handler, that you pass to the input. If you have a more specific question, please edit your question to make that clearer. – Robin Zigmond Jun 13 '22 at 19:37
  • _ even though no onchange function is write in this program_ - yes there is! `onChange: event => setValue(event.target.value)` – moonwave99 Oct 08 '22 at 15:37

1 Answers1

0

Functions in JS are treated like any other variable. So the de-structured onChange (in the component) is taking the reference for a function which is defined anonymously in the custom hook, which is then used by the onChange method of the TextField component. This is similar to how you pass variables by reference is JS.

  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Oct 13 '22 at 02:58