Home > Back-end >  Good Practices in ReactJs for Shared Values ​in the Application
Good Practices in ReactJs for Shared Values ​in the Application

Time:12-25

I have some experience in software development, but i am new in React and I need in my system to share a constant value that will be used in several components.

therefore, I thought who would create an object containing several constant values ​​that I will use in several places

My doubt is, would this be good practice?

I'm aware of the context in react, but I think it would be a little too much to use it

CodePudding user response:

If the shared value is going to stay constant you can create a file like constant.js and store values there (in case of storing database uris, port or jwt secrets use .env instead). It the shared value is going to change i.e. variables then you can use redux or context APIs.

CodePudding user response:

If its a constant values that will never change, just create a .js file and import them there, then export it wherever, because Context API or Redux is for state management, and in your case, you dont have states to manage, so I would go for the .js file idea.

CodePudding user response:

Let's assume there are different types of constants:

The approach I would follow is-

Create constants/ folder and follow below structure

- constants
    - TextConstants.js
    - StyleConstants.js
    - ... and more
    - index.js

For files like TextConstants, StyleConstants etc...

export const Text1 = 'Text1';
export const Text2 = 'This is text 2';

In constants/index.js -

export * from './TextConstants';
export * from './StyleConstants';

And you can import where you want (say App.js) as following-

import { Text1 } from './constants';
  • Related