With selectors, you have given your application the instructions to access data from the Redux store. To use these instructions the useSelector()
hook is provided by react-redux
. useSelector()
accomplishes two things:
- It returns data from the Redux store using selectors
- It subscribes a child component of
<Provider />
to changes in the store. React, not Redux, will re-render the component if the data from the selector changes.
These tasks are both accomplished by calling useSelector()
inside a component definition and assigning its returned value to a variable.
// Todos.js import { useSelector } from 'react-redux'; import { selectTodos } from 'todosSlice.js'; export const Todos = () => { const todos = useSelector(selectTodos); return ( <p>{todos}</p> ) };
In the above example, useSelector()
takes the imported selector function selectTodos
as an argument. The returned value is the selected data from the Redux store and is assigned to todos
.
Calling useSelector()
inside the component definition also subscribes the Todos
component to re-render if any changes occur in the todos
portion of the Redux store. This optimizes the performance of the application by only re-rendering components that have had their data change and not the entire application.
useSelector()
can also use an inline selector as an argument:
const todos = useSelector(state => state.todos);
Inline selectors can be useful if you need to use props for data retrieval.
export const Todo = (props) => { const todo = useSelector(state => state.todos[props.id]);
This final example uses props.id
to extract a single element from an array or object in the Redux store.
useSelector()
completes the 3 step process for accessing data from the Redux store using react-redux
.
- The
<Provider>
component is used to provide the Redux store to the nested application. - Selectors are created to give instructions on retrieving data from the store.
useSelector()
is called within a child component of<Provider>
for executing selector instructions to retrieve data and subscribe to re-rendering.
Instructions
To access Redux store data with useSelector()
, you first need to import it from react-redux
.
In AllRecipes.js import useSelector
from react-redux
.
Along with useSelector()
you need access to the selectFilteredAllRecipes
selector defined in the previous exercise.
In AllRecipes.js add selectFilteredAllRecipes
to the allRecipesSlice.js import statement.
With both import statements complete, you are now able to access the data using the selector function and useSelector()
.
Inside the AllRecipes()
component function:
- Define a variable
allRecipes
. - Assign it the value returned by
useSelector()
. - Pass
selectFilteredAllRecipes
touseSelector()
.
In this exercise, the data was initialized with recipes so when you run the code you should see the recipe data rendered in the browser.