Where should I hold constant non changing data

(Ben Carp) #1

I’m building react components (with Redux) and embed them in our backend template files.
I’m not sure what is the appropriate place to hold some constant data, that though it does need to be displayed/rendered in some way or another, it doesn’t change through out the lifetime of the application, and therefor we shouldn’t really followup with them. An example is a map/object that links between a state and it’s region ({Canada: “North America”…}).
It doesn’t seem to belong to the state, but on the other hand I don’t won’t to interrupt the one direction data flow of React-Redux. There are other examples as well. I consider having one const object, with an interface, which can be accessed by the different components which need to use it, and it might even be accessed by the reducer for calculations.

(Troy Rhinehart) #2

I’d say don’t overthink it. Have a constants directory w/ files describing the content and bring via a normal import/require.

// components/Thing.js
import React from 'react';
import region from '../constants/regions';
export default function Thing (props) {
  return <h1>{ region[props.id] }</h1>;

(Agnivesh Patel) #3

I think contexts would be useful here.

(Daniel K.) #4
import React from 'react';

export const constants = {
  countries: {...}

export const { Consumer: Constants } = React.createContext(constants)

/* some other file with a component */

import { Constants } from './constants'

export const props => (
  <Constants>{({ countries }) => <h1>{countries[props.id]}</h1></Constants>

You can either import the constants object directly (I would probably Object.freeze it) or import the component. One might wonder what is the benefit of such component? Well, an encapsulation is a good thing in overall. Later if you would need to eg. load those countries from some async source, you can refactor this more easily. Also coupled with a Provider, it’s easy to override those constants which might be valuable in automated tests.

(Ben Carp) #6

My question was more about how to organize the app. Anyway thanks for your responses.