1

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.

5
  • I wanted to suggest local storage, you can get and modify it in every component ,what is the problem with it? Commented Sep 24, 2019 at 10:44
  • You can use Context API or something like Redux or simply write in window Commented Sep 24, 2019 at 10:45
  • By using localstorage. Problem is when do logout and log in, into application the values are still exists Commented Sep 24, 2019 at 10:55
  • global variable in React is to put it on the window Answer: stackoverflow.com/questions/45080011/global-variable-for-react Commented Sep 24, 2019 at 11:03
  • Well clear the localstorage at login and/or logout. Commented Sep 24, 2019 at 11:18

1 Answer 1

0

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.

  1. Store your data in the topmost component state and pass it to the child components via property.

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

  3. 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)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.