Should I define model classes?

TomR picture TomR · Jun 16, 2019 · Viewed 10.1k times · Source

React uses Flux architecture and it is said in https://reactjs.org/docs/thinking-in-react.html that React has two models - state and props. And there are some suggestions for model management in React https://reactjs.org/community/model-management.html - but all of this seems to some additional layers to enhance the Flux. The big questions to which I am seeking the answers are:

  • Should I define model classes in React? I.e. if I have Customer class notion, then I can: 1) define the attributes of Customer directly as the attributes of state/props 2) define the attributes of Customer as the attributes of state.customer/props.customer; 3) define some JavaScript template/class Customer separately and simply say, that state.customer/props.customer is of type Customer and don't repeat attributes in the state/props. I feel, that 3) is the right approach, isn't it?
  • If 3rd options (of the previous point) is the right approach, then how can I define the Customer template and how can I define that state.customer/props.customer is of this template? I could use those template in some serialization, some model validation tasks as well and I could use in ReactNative project as well.

Answer

Neskews picture Neskews · Jun 16, 2019

The most basic way is shown in following snippet:

const Customer = ({ name, age }) => (
  <div>
    <p>Name: {name}</p>
    <p>Age: {age}</p>
  </div>
);

const App = () =>
  [{ name: "Bert", age: 22 }, { name: "Alfons", age: 45 }].map(
    ({ name, age }, i) => (
      <>
        <Customer key={i} name={name} age={age} />
        <hr />
      </>
    )
  );

Where you define these props depends on where you need them. If only one component needs the props, you define them in that components state. But often you need the props in several components, so you lift them in your hierarchy up. That often results in a very "smart" component (a component that has a large state).

If your app becomes large and confusing, I suggest you store your state externally. To do that, you can use react context. It allows you to inject props to components that need it, rather than passing it several layers down in your hierarchy.

If you don't want to write your own context, you may use state management solutions like redux or mobx. They use context too, but provide convenient functions to easily connect a component to your external state.