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

book
Using 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:

js
import React from 'react';
import { createRoot } from 'react-dom/client';
import { Provider } from 'react-redux';
import { store } from './app/store';
function App(props) {
return (
<div>
<h1>Todo Application Using Redux</h1>
<form>
<ul>
{/* Need to display Todo items here */}
</ul>
<input></input>
<button>Add</button>
</form>
</div>
);
}
createRoot(document.getElementById('root'))
.render(
<React.StrictMode>
<Provider store={store}>
<App />
</Provider>
</React.StrictMode>
);

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:

js
export const selectTodos = (state) => state.todos;

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:

js
{
todos: [
"Finish the application"
]
}

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

js
import { selectTodos } from './todosSlice';

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

js
import { Provider, 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:

js
let todos = useSelector(selectTodos);

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

js
<ul>
{todos.map((item, index) => <li key={index}>{item}</li>)}
</ul>

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.

question mark

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

import { useSelector } from 'react-redux';
import { selectValue } from 'featureSlice';

function App() {
const value = ___
return (
<h1>The value is {value}</h1>
);
}

Select the correct answer

Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 3. Chapter 7

Ask AI

expand

Ask AI

ChatGPT

Ask anything or try one of the suggested questions to begin our chat

We use cookies to make your experience better!
some-alt