Global Store

You decide to name your quotations app Quotebase. As with your previous app, you use the create-react-app utility to start a new project, install the Redux dependency, and load up the live preview in your browser:

npx create-react-app quotebase
cd quotebase
npm install react-redux
npm run start

You clean up the starter app by getting rid of the code and files you don't need. Before diving into the interface, you turn your attention to creating a global store to hold the state that will be shared across all components of your app.

The shared state consists of a collection of quotations organized by their authors. Additionally, it will store the name of the author whose quotations are currently being viewed. When the app first starts up, the state looks like this:

const initialState = {
quotations: {
"Condoleeza Rice": [
"I firmly believe you never should spend your time being the former anything.",
"We need a common enemy to unite us.",
],
"Audre Lord": [
"When we speak we are afraid our words will not be heard or welcomed. But when we are silent, we are still afraid. So it is better to speak.",
"It is not our differences that divide us. It is our inability to recognize, accept, and celebrate those differences.",
"The master's tools will never dismantle the master's house.",
],
},
selectedAuthor: null,
};

There are five quotations, and no author is currently selected. Eventually you will have hundreds of quotations. But this is enough for a prototype. You place this object in a file named store.js in the src directory. The store is not a component, so store.js is not capitalized.

Redux provides a createStore function that you use to create the global store. But you don't populate it with your initialState directly. Instead you define a function whose job is to return the state. This function is conventionally named reducer. You hand it and the initial state object off to createStore:

import {createStore} from 'redux';

const initialState = {
// ...
};

function reducer(state) {
return state;
}

export const store = createStore(reducer, initialState);

Right now, reducer is a silly function that does nothing. It will get less silly when you start changing the shared state.

The store is exported. You open up index.js and add a component that will make this store available in all components that are descendents of App. The component's name is Provider. You must import it and nest App inside of it in the JSX:

// ...
import {Provider} from 'react-redux';
import {store} from './store';

ReactDOM.render(
<React.StrictMode>
<Provider store={store}>
<App />
</Provider>
</React.StrictMode>,
document.getElementById('root')
);

The store is attached to Provider as a prop. Quotebase now has a global store holding all the quotations and the name of selected author. The next step is to get a component to read from the store.