D
D
Durin Qurkingo2019-08-11 14:57:00
React
Durin Qurkingo, 2019-08-11 14:57:00

useEffect hook, how to use props but not update them?

I'm using the useEffect hook to trigger some actions when the component mounts.
Here is the code:

useEffect(() => {
    onChange(
      bar1 ? graphData.displayedItems[bar1.value] : null,
      bar2 ? graphData.displayedItems[bar2.value] : null,
      by ? byOptions[by.value] : null
    )
  }, [])

This code works fine, but I get a warning:
Line 54: React Hook useEffect has no dependencies: 'bar1', 'bar2', 'by', 'byOptions' and 'graphData.displayedItems'. Either include them or remove the dependent react-hooks / exhaustive-deps array.
I don't want to add them to the dependencies array because that way it will run every time one of those props is updated. And I just want to run once when the component mounts.
Is there a way to get rid of the warning without adding them to the dependencies array?
I know this warning can be overwritten by the ESLint config. But I don't want it; I want the right solution. If React added this warning, there should be a solution for this.
I am learning to use hooks. It's really? Should I use componentDidUpdate in this case?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Spirin, 2019-08-11
@Sagund

If React added this warning, there should be a solution for this.

This warning is added by ESLint. If you do not want to disable the rule globally, you can use comments to disable it in a specific block.
ESLint: Disabling Rules with Inline Comments

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question