M
M
miliko mikoyan2019-07-07 17:33:57
React
miliko mikoyan, 2019-07-07 17:33:57

Is it necessary to use useMemo in hooks?

i created useBanner hooks

const useBanner = (array, yardage) => {
  const [bannArr, setBannArr] = useState(array.slice(0, yardage));
  const [bannListIndex, setBannIndex] = useState(1);

  return {
   ....
  };
};

Am I doing the right thing by throwing the value and props into useState ?
allowable i use useBanner.
const Banner= ({
  array,
  yardage
}) => {
  const { bannForth, bannBeck, bannArr } = useBanner(array, yardage);
  return (
    ...
  );
};

when props change here.
Will the state change in useBanner.
or is this considered an antipattern I should write it all in useMemo
const useBanner = (array, yardage) => {
  const [bannArr, setBannArr] = useState([]);
  const [bannListIndex, setBannIndex] = useState(1);

 useMemo(() => {
    setBannArr(array.slice(0, yardage));
    setBannIndex(1);
  }, [array, yardage]);

 
  return {
   ....
  };
};

Answer the question

In order to leave comments, you need to log in

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

For expensive operations, it's better to use lazy state initialization:

const useBanner = (array, yardage) => {
  const [bannArr, setBannArr] = useState(() => array.slice(0, yardage));
  const [bannListIndex, setBannIndex] = useState(1);

  return {
   ....
  };
};

I don't think there will be any performance benefit in the first hook.
In the second, lazy initialization is meaningless.

R
Robur, 2019-07-07
@Robur

I already gave the correct answer here: If props is missing Do I need to use memo?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question