M
M
miliko mikoyan2019-07-07 01:32:20
React
miliko mikoyan, 2019-07-07 01:32:20

React Hook useCallback has an unnecessary dependency: 'price'. Either exclude it or remove the dependency array.?

import ReactDOM from "react-dom";
import React, { Fragment, useState, useCallback } from "react";

const ProcessingSearch = () => {
  const [price, setPrice] = useState({ maxPrice: 0, minPrice: 0 });
  const [solde, setSolde] = useState(0);
  const inputMaxMin = useCallback(
    ({ target: { value, name } }) => {
      name === "maxPrice"
        ? setPrice(({ minPrice }) => ({ maxPrice: value, minPrice }))
        : setPrice(({ maxPrice }) => ({ minPrice: value, maxPrice }));
    },
    [price]
  );

  return (
    <Fragment>
      <form onSubmit={() => {}}>
        {"Min"}
        <input value={price.minPrice} onChange={inputMaxMin} />
        {"Max"}
        <input value={price.maxPrice} onChange={inputMaxMin} />
        <input type="submit" title={"Submit price range"} value={"Go"} />
      </form>
      <div onClick={() => setSolde(solde + 1)}>{solde}</div>
    </Fragment>
  );
};

const rootElement = document.getElementById("root");
ReactDOM.render(<ProcessingSearch />, rootElement);

When I use price I get an error:
React Hook useCallback has an unnecessary dependency: 'price'. Either exclude it or remove the dependency array.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Spirin, 2019-07-07
@miliko0022

Your inputMaxMin callback is overridden by the change in price, but this is not necessary, since this value is not used in the callback. Just pass an empty array as the second argument:

const inputMaxMin = useCallback(
  ({ target: { value, name } }) => {
    name === "maxPrice"
      ? setPrice(({ minPrice }) => ({ maxPrice: value, minPrice }))
      : setPrice(({ maxPrice }) => ({ minPrice: value, maxPrice }));
  },
  [],
);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question