3

With the old class-based this.setState() method, we could return null from a function passed to setState to tell React not to do anything with that specific setState call:

this.setState(({ value }) => {
  if (value === 0) {
    return null;
  } else {
    return { value: value - 1 };
  }
});

I'm trying to understand what's the correct way to do this with React Hooks, is the below correct?

const [x, setValue] = useState(0);
setValue(value => {
  if (value === 0) {
    return value;
  } else {
    return value - 1;
  }
});

I'm trying not to trigger a re-render if I pass the original value.

Fez Vrasta
  • 14,110
  • 21
  • 98
  • 160
  • 1
    @NikitaMadeev see https://blog.logrocket.com/returning-null-from-setstate-in-react-16-5fdb1c35d457/ – Fez Vrasta Aug 06 '20 at 11:34
  • Oh, did not know about this possibility. Then your solution looks to work because [If you update a State Hook to the same value as the current state, React will bail out without rendering the children or firing effects](https://reactjs.org/docs/hooks-reference.html#bailing-out-of-a-state-update) – Nikita Madeev Aug 06 '20 at 11:44
  • [Similar question](https://stackoverflow.com/questions/55373878/what-are-the-differences-when-re-rendering-after-state-was-set-with-hooks-compar) – Nikita Madeev Aug 06 '20 at 11:52

2 Answers2

0

Looks like a job for useEffect hook:

useEffect(() => {
setValue(value => {
  if (value === 0) {
    return value;
  } else {
    return value - 1;
  }
});
}, [x])

Effect will only run if x changes.

Michał Lach
  • 1,291
  • 4
  • 18
  • 37
0

React shouldn't rerender. From react docs (https://reactjs.org/docs/hooks-state.html): "If your update function returns the exact same value as the current state, the subsequent rerender will be skipped completely."

tornord
  • 336
  • 4
  • 8