Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Using Selectors to access State | Redux in Practice
Introduction to Redux
course content

Course Content

Introduction to Redux

Introduction to Redux

1. Getting Started
2. Fundamental Concepts
3. Redux in Practice
4. Creating a React-Redux Application

bookUsing Selectors to access State

We don't have direct access to the store from index.js or other React component files, so we often create selectors to access the state data.

Following is an index.js script in which we need to access the items in the Todo list from the Redux store to display them on the page:

For that, we can create a selector function. We often create selector functions in the relevant file hence, for extracting data from todo, we create and export the function from todosSlice. We add this at the end of todosSlice:

It's a simple inline function that takes in a state object and returns a specific part of it: the data in the todos key. Recall that the structure of the Todo app's state looks something like this:

After that, we can now import the selector function inside index.js:

We also need to import a function called useSelector from react-redux:

Now to use the selector function, we need to call the useSelector function and pass the selector function selections as an argument. The returned data will be the data we need:

We can then simply use the map method of the todos array to map the items in the form of <ul> elements:

Following is a sandbox version of the final code. Drag from the left to see the code:

To recap, we created and exported a selector function that returned the data from the todo slice and used it with the help of useSelector function.

Select the correct option to complete the code in line 4.

Select the correct option to complete the code in line 4.

Select the correct answer

Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 3. Chapter 7
We're sorry to hear that something went wrong. What happened?
some-alt