How to create a global variable in react js - reactjs

How to create a global variable in react component,so that all the other react component can access that global variable and modify it,and for every new request the global variable data should not be lost.
I have tried
localStorage.setItem('key',value)
this is working fine. But problem is By using localstorage. when do logout and log in, into application the values are still exists.

I do not recommend using global variables in React. When you store something in a global variable and you can modify it from everywhere it is against the philosophy of React.
But you can use more option which is in line with React and can access it form plenty of places. And all of the option provides re rendering when the this global value change.
Store your data in the topmost component state and pass it to the child components via property.
Store your data in the topmost component state and use Context to access it from a deep down child component without passing the data in properties trough the component hierarchy.
Use redux. It is an overkill sometimes and has a steeper learning curve, but you can access the centralized redux data from every component and every level. (it uses Context too)

Related

State Variables vs Redux in React

Which one of the two scenarios is preferred?
Use state variables to store the value from the backend/server and use it directly in all the components(Eg: DataTable) present on the Page.
While calling the APIs, that data will load in Redux store. So instead use the data from the redux store directly in all the components.
Case 1 : When to use Local React State
React state is stored locally within a component. When it needs to be shared with other components, it is passed down through props. In practice, this means that the top-most component in your app needing access to a mutable value will hold that value in its state. If it can be mutated by subcomponents, you must pass a callback to handle the change into subcomponents.
Case 2 : When to use Redux state management
When using Redux, state is stored globally in the Redux store. Any component that needs access to a value may subscribe to the store and gain access to that value. Typically, this is done using container components. This centralizes all data but makes it very easy for a component to get the state it needs, without surrounding components knowing of its needs.
Case 2 should be preferred.
When the data is used in multiple components and is coming from the backend, you should store it in a redux state.
Keep any state that can be called "Application State" in the redux. If that object somehow is defining some part of your application and not just a state of a component(e.g. showSpinner, isEditMode, etc) then it's your applications state and should be kept in the redux store. That's kind of my definition of difference. Also, note that you should always keep only JSON serializable object in your redux store. Also, I mostly consider data from backend to be a part of "Application State".
So I think that your data should be stored in redux. Technically you have on advantage when using redux store in your case as redux triggers component updates only when the data is changed. So using it here might give you some performance benefits as well.

Can I use state in components while using Redux or Redux store?

**Is it OK to Using a component state for just to handling form data, while the main data and other stuff of the application will be stored in the Redux store?
I don't want to use redux-form instead manually dispatch it to the reducers**
Redux comes into the picture when we want to manage the state across different component. It provides a centralize store where state of all the components are managed.
When talking about forms, in most cases form data is only limited to the component is which is being used. So, in that type of scenario there is no need to link them to centralized store using redux. A simple way is to store them in the component state and get it processed. Afterwards, you can store the output of that in redux store according to your needs.
It is okay to do that. You can keep a local state in the component. state = {} in class components, const [localState, setLocalState] = useState() for functional components.
Or you can use custom hooks for handling your local state needs. Check out useInput or useForm custom hooks that are developed by the community.
Yes of course. Some things go best in component state, some go best in a parent component, some go in Context, and some go in Redux. There is little use in putting everything in Redux, it just causes a lot of boilerplate and every component tries to update when the store changes.
You put things in Redux when different components that are at different places in the HTML tree use the same data, and it changes during the app's lifetime (things like the user's language don't change often and go in Context). You use it when you want to store your app's state to restore it later (which exact menus are currently open or closed is usually not that important) and when you want to keep track of state changing using the Redux dev tools.

Should I use Redux when component state is local

I have a component which has some local state (form validation error messages). This component does not get its state from a parent, nor does it passes these values to any of its children.
My application uses Redux for global state management. Should I push this state to be managed via Redux, or keep using local state for this particular component.
The simple answer is NO. -Simply because you already have all the necessary data in the only relevant component where you're actually using it.
Redux (react-redux) is used for app level state management.
So, here comes the longer answer -If you at some point decide that you need the data in various components and also that they need/ should be accessible at any point, Redux is definitely a great option.
It all really depends on the amount of data and the need for effectively passing the data throughout the entire app.
On the other hand, if you only have to pass data between Parent - Children components, Redux could be an overkill, because you can still achieve it using just React by passing (exchange) values between various components via props.
So, if you only need that data inside only that component (Component level state), Redux it's a no-go because it's pretty large and it wouldn't be of any use for your case.
Sounds like the data is only needed for this component, so you don't need to push it to the Redux state.
Yes, if you take the way of an immutable state and connected components and you would avoid unecessary re-render.
In this case, you can connect your field to it's state, and rerender the error message only when an error occur.
I would not save this to Redux state.
Unless you require this data elsewhere.

How to save any value globally in the project so that we can access it from anywhere in react.js

We need to save a value globally so we could access it from any component.
How can we do it properly?
I have tried it in many ways
1- make a component and store value in it. and import from other components where you need to use it
I have also tried props and state concept that would work in the parent-child flow of data.
-- Use Redux for easier state management for application-level state
-- use react store for component level state management
If you don't want to use an external library you can just use the context of react.
https://reactjs.org/docs/context.html
But when your application scales redux is probably the best way to do it
You'll want to use a state manager like Redux or Mobx to manage your state outside of their component scope.

Should you store Application state in local state or Redux Store

I have been working with Redux for almost a month now. My question is this that I am putting all my app data in the redux store, but should I also put the toggle states that helps me change my UI in redux state or should I simply manage that locally in each page by just doing
this.setState({ showActiveForm : false })
There is no right or wrong answer for this. To help you decide, here are some common rules of thumb taken directly from the redux documentation:
Do other parts of the application care about this data?
Do you need to be able to create further derived data based on this original data?
Is the same data being used to drive multiple components?
Is there value to you in being able to restore this state to a given
point in time (ie, time travel debugging)?
Do you want to cache the data (ie, use what's in state if it's already there instead of re-requesting it)?
Another advantage to keeping the majority of your UI state in redux is that you can write more stateless functional components and make use of the performance optimisations they will bring in future versions of React:
This pattern is designed to encourage the creation of these simple components that should comprise large portions of your apps. In the future, we’ll also be able to make performance optimizations specific to these components by avoiding unnecessary checks and memory allocations.
The current best practice is to use local state to handle the state of your user interface (UI) state rather than data.
Your case is the perfect example of the above. So the state to manage hiding and showing of a component must be within the local state itself and not redux store
Another example of UI data that you could store in local state would be the currently selected tab from a list of options.
A good way to think about when to use local state is to consider whether the value you’re storing will be used by another component. If a value is specific to only a single component, then it’s safe to keep that value in local state.
To elaborate further
Redux is also useful for triggering events for which you need access on multiple components or across multiple routes. An example of this would be a login modal, which can be triggered by a multitude of buttons all across your app. Rather than conditionally rendering a modal in a dozen places, you can conditionally render it at the top-level of your app and use a Redux action to trigger it by changing a value in the store.
Usually, the rule of thumb is that you use a redux store to manage data in your application aka storing items fetched from the server and local react state for ui behaviors, like toggles in your case. But it's not a strict rule, for instance, if you need to toggle something from multiple places it's easier to use redux for that
That depends on how your components are organized. If the state of toggle is used across multiple components then I prefer to manage the state via redux store.
If the the status is local to that component and if it is not used in anywhere else best thing to do would be managing the state within the component. Therefore the component will be self contained.
3 points that i consider when working with react redux
1.keep UI state and transitory data (such as form inputs) in local state.
2.keep data that you intend to share across components in Redux store.
3.Data that you fetch from Server should go to redux store.

Resources