Get ready for your next interview with our comprehensive question library
The Redux store is a single JavaScript object that holds the complete state tree of your application. It provides methods to:
getState()
: Returns current statedispatch(action)
: Dispatches an action to trigger state changesubscribe(listener)
: Registers a listener functionimport { createStore } from 'redux';
const store = createStore(reducer);
Actions are plain JavaScript objects that describe what happened in the application. They must have a type
property and can contain additional data (payload).
// Action object
const addTodo = {
type: 'ADD_TODO',
payload: {
id: 1,
text: 'Learn Redux'
}
};
// Action creator function
const addTodoAction = (text) => ({
type: 'ADD_TODO',
payload: { id: Date.now(), text }
});
Reducers are pure functions that take the current state and an action, and return a new state. They specify how the application's state changes in response to actions.
const todosReducer = (state = [], action) => {
switch (action.type) {
case 'ADD_TODO':
return [...state, action.payload];
case 'REMOVE_TODO':
return state.filter(todo => todo.id !== action.payload.id);
default:
return state;
}
};
type
property// Action
const action = { type: 'INCREMENT', payload: 1 };
// Action creator
const increment = (value) => ({
type: 'INCREMENT',
payload: value
});
Using React-Redux library:
Provider
componentuseSelector
hook to read stateuseDispatch
hook to dispatch actions// App.js
import { Provider } from 'react-redux';
<Provider store={store}>
<App />
</Provider>
// Component
import { useSelector, useDispatch } from 'react-redux';
const todos = useSelector(state => state.todos);
const dispatch = useDispatch();
The Provider component makes the Redux store available to all nested components. It uses React's context API to pass the store down the component tree without manual prop passing.
Upgrade to Premium to see the answer
Upgrade to PremiumUpgrade to Premium to see the answer
Upgrade to PremiumUpgrade to Premium to see the answer
Upgrade to PremiumUpgrade to Premium to see the answer
Upgrade to PremiumUpgrade to Premium to see the answer
Upgrade to PremiumUpgrade to Premium to see the answer
Upgrade to PremiumUpgrade to Premium to see the answer
Upgrade to PremiumUpgrade to Premium to see the answer
Upgrade to PremiumUpgrade to Premium to see the answer
Upgrade to PremiumUpgrade to Premium to see the answer
Upgrade to PremiumUpgrade to Premium to see the answer
Upgrade to PremiumUpgrade to Premium to see the answer
Upgrade to PremiumUpgrade to Premium to see the answer
Upgrade to PremiumAccess all premium content - interview questions, and other learning resources
We regularly update our features and content, to ensure you get the most relevant and updated premium content.
1000 monthly credits
Cancel anytime