Optimizing Component Renders with Selectors
Explain using selectors in custom hooks to derive state and optimize component rerenders by preventing unnecessary updates.
const store = createStore({
initialState: {
todos: [],
filter: 'all'
},
actions: {
setFilter(state, filter) {
state.filter = filter;
},
addTodo(state, todo) {
state.todos.push(todo);
}
},
selectors: {
filteredTodos(state) {
switch (state.filter) {
case 'completed':
return state.todos.filter(todo => todo.completed);
case 'active':
return state.todos.filter(todo => !todo.completed);
default:
return state.todos;
}
}
}
});
This code initializes a store with state containing 'todos' and a 'filter'. It defines actions to set the filter and add a todo, and a selector 'filteredTodos' that computes todos based on the filter.
function useFilteredTodos() {
const filteredTodos = store.useSelector(store.selectors.filteredTodos);
return filteredTodos;
}
This custom hook uses the 'useSelector' hook provided by the store to access the 'filteredTodos' selector. By using this selector, the component subscribing to this hook only re-renders when the filtered todos change, not on every state change.