Home > Software design >  How to pass a method into a child element if the method relies on state variables in React
How to pass a method into a child element if the method relies on state variables in React

Time:04-05

I've been learning react over the last few days and for the most part it makes sense, however there is one thing that is stumping me.

If I have

  • A Parent element with some state variables and a callback method
  • A child element that takes a callback method as a prop
  • The callback method relies on some piece of state that is in the parent element
  • I don't want to re-create the view object every time any state changes

Every time I try to do this, it seems like the child element is calling some older version of the parent element (presumably the instance of the parent that actually created the child) instead of the current version.

I'm getting the feeling that what I want is just wrong on a fundamental level and isnt The React Way

The reason that I am trying to do this is that my main parent contains 17 divs, each of which represent a key on a musical instrument, and each of which contains at least 20-30 divs. The lowest div (of which there are at least a few hundred) has an onClick event that I want to modify the functionality of based on whether modifier keys are held down (shift, control etc).

Currently I have Raised the state of the shiftPressed to be on the single parent element then passed down the value of that into each child through props, however re-rendering hundreds of divs whenever a user pushes shift takes quite a while.

I've made a code sandbox to show the current problem Edit how-to-pass-a-method-into-a-child-element-if-the-method-relies-on-state-variable

It's also generally considered anti-pattern to use any sort of "forceUpdate" function and is a code smell. In almost all circumstances if you hit a point where you need to force React to rerender you are doing something incorrect. This is the time you step back and trace through your code to find where a certain piece of state or some prop isn't updated correctly to trigger a rerender naturally.

  • Related