javascriptreactjsclassreact-nativeflux

Should I define model classes in React?


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:


Solution

  • 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.