Q:

how to pass global variables to all components - react js

I have a shopping cart website and I should pass some value to all components.  for example when the user logged in the website I stored some value of user to localStorage.  now, most components need to know about these values. 
my question is I should retrieve these values inside each component (inside componentDidMount function)? 
of course I know about redux.  but I have a problem with redux when the user refresh page I lose data. 

A:

If you use redux.  You can persist and rehydrate the store to the local storage or IndexedDB using a store enhancer, such as redux-persist. 
Another option is to use Use React's context.  You can inject the data to the component's tree via the context provider, and all components would have access to it. 
The context is described as:

Context provides a way to pass data through the component tree without
  having to pass props down manually at every level. 

Example of use (from React 16.3 documentation):
// Create a context for the current theme (with "light" as the default). 
const ThemeContext = React.createContext('light');

class App extends React. Component {
  render() {
    // Use a Provider to pass the current theme to the tree below. 
    // Any component can read it, no matter how deep it is. 
    // In this example, we're passing "dark" as the current value. 
    return (
      <ThemeContext. Provider value="dark">
        <Toolbar />
      </ThemeContext. Provider>
    );
  }
}

function ThemedButton(props) {
  // Use a Consumer to read the current theme context. 
  // React will find the closest theme Provider above and use its value. 
  // In this example, the current theme is "dark". 
  return (
    <ThemeContext. Consumer>
      {theme => <Button {...props} theme={theme} />}
    </ThemeContext. Consumer>
  );
}

