M
M
McHack2021-01-21 13:33:31
React
McHack, 2021-01-21 13:33:31

How to declare a shared variable in React and use it to render individual components?

Hello gentlemen. I'm making a horizontal menu in React and I'm having trouble re-rendering something that doesn't need to be re-rendered. I write on functional components!

Having this structure:

// MenuItem - отдельный дочерний компонент для каждого пункта меню
// showChild - переменная в которой хранится ID главного пункта, где должны отобразиться дочерние элементы

сonst [showChild, setShowChild] = useState(null)

const toggleMenu = (id, with_child, fl, e) => {
    if(with_child !== '' && fl) {
      if (showChild !== id)
        setShowChild(id)
      else {
        Fade.Out('.j_h_menu_child_sub[id="' + id + '"]', 200, function () {
          setShowChild(null)
        })
      }

      e.preventDefault()
    }
    else
      return true
  }

return (
    <div className="i_h_menu_react">
      {items.map((item) =>
        <MenuItem item={item} key={item.ID} showChild={showChild} setShowChild={toggleMenu} ww_mob={ww_mob}/>
      )}
    </div>
  )


PS I specifically posted only part of the code in order to simplify the understanding of the process.

Through the child component, I call a function that changes showChild by substituting a different ID there. I need this approach so that the child elements are displayed only in the clicked item, and in the rest they are hidden. When calling to another point, the old daughters disappeared and appeared in another point.

However, updating showChild React with a new one renders absolutely all components. Roughly speaking, it starts the cycle in the template over a new one. Respectively there is a Mount of all components on new.

How do I declare a variable that would be stored in the main component and not trigger a re-render when it changes. But such that I can track its change in child components and, accordingly, start re-rendering only in the component I need.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry, 2021-01-21
@dimoff66

You declare an ordinary object type variable and push it to the children through properties or through useContext . In any of its properties, write the value you need, this will not start updates. And add a timeout that tracks the change.
This is of course if you do not use redux
But in general it is not clear what is the problem of re-rendering all children? Do you have so many of them that the application slows down or what?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question