Joseph Padgett
Joseph Padgett

Reputation: 27

How do I make react hookstate.js stop rerendering when using .set?

I have a state object already set in hookstate. In a particular file, I have the following calling it:

const druidPowers = useDruidPowersState(druidPowersState)

  useEffect(() => {
   Axios.get('http://localhost:5000/powers/druidpowers/levelone')
    .then((data) => {
        const powersData = data.data.druidpowers[0].powers.levelOne
        druidPowers.shapeshift.set(powersData.shapeshift)
        druidPowers.naturesBoon.set(powersData.naturesBoon)
    })
  }, [druidPowers.shapeshift, druidPowers.naturesBoon])

  druidPowers.shapeshift.powerUsage.set({
      powerUse: {
        hp: (characterHp, body, spirit) => {
          characterHp += (body + spirit)
        }
      }
    })
  
  console.log(druidPowers, 'druid powers')

The code inside the useEffect does what I intend no issues. It's when I add in the .set() outside of the useEffect that becomes the issue. Console confirms this is updating it for me. However, it also confirms that it won't stop console.log()'ing it. I tried, just on random chance, to put a , [] in there like you would on a useEffect, but that didn't stop it, so just wondering if anyone knows why it keeps doing it.

Upvotes: 1

Views: 195

Answers (1)

Andrew
Andrew

Reputation: 2135

Author of Hookstate is here. State instances are refreshed on each rerender, so your effect is triggered on each rerender. Replace [druidPowers.shapeshift, druidPowers.naturesBoon] by [] and will stop running the effect. ES Lint complaints can be suppressed for this line.

Also, please see related ticket: https://github.com/avkonst/hookstate/issues/140

Upvotes: 1

Related Questions