Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using React without States

I am building the UI of an app and I am exploring updating the UI without having to use States. Would the following assertion be crudely correct?

'We do not need States as all its doing is calling the render method automatically on the component when something within the state changes. We can achieve the same implementation by calling the render method on the relevant component ourselves.

We would still achieve all the same benefits of React (virtual DOM, rendering, painting optimisations etc)'

like image 700
Kayote Avatar asked Feb 09 '23 02:02

Kayote


1 Answers

It is technically correct that you do not need to use React's internal component state to build a React application. Of course, the data needs to live somewhere, so you need a mechanism which can pass all the data into the top-level component (where it will trickle down into all the other components) when the data changes.

This is the basic idea behind flux (and many other patterns designed to provide outside-of-React state storage). You have one or more stores and the stores provide change events when their data changes. Then that data gets passed into the application via props.

function render(data) {
  ReactDOM.render(
    <Application data={data} />,
    containerNode
  )
}

myDataStore.on('change', render);

In practice, however, it can be difficult to do this performantly because of how JavaScript works. Code like the above would make React re-render the entire component tree each time myDataStore changes, and without good shouldComponentUpdate hooks, this can be a performance issue. Using immutable values helps make it easier to implement good shouldComponentUpdate methods.

What you'll usually see in a larger React application that uses outside-of-React data storage is a combination of:

  • One or more "container" components that are responsible for getting the data from the stores and passing it to their children. Sometimes it makes sense to put containers somewhere other than the very top of the component tree (e.g. you may have several containers in one app)
  • Reusable/"presentational" components that do not hook into the data store, but provide some other benefit (such as black boxed styles, or an interactive widget). In these cases, it often makes sense to keep any non-application-specific state inside the component itself.
like image 126
Michelle Tilley Avatar answered Feb 13 '23 14:02

Michelle Tilley