A Simple Guide to Redux
Redux is a tool used in JavaScript applications for managing state. It helps make the behavior of your app predictable and easy to understand.
Here are the basic concepts you need to know:
Store
The store is like a container that holds your app’s state. There’s only one store in a Redux app.
State
The state is a JavaScript object that represents your app’s data. It’s stored in the Redux store.
Action
Actions are JavaScript objects that tell Redux something happened in your app.
They have a type property and sometimes extra data. For example, an action might look like this:
{
type: 'ADD_TODO',
text: 'Learn Redux'
}
Reducer
Reducers are functions that take the current state and an action, and return a new state.
They describe how the state should change in response to an action.
Here’s a simple reducer for a counter:
function counter(state = 0, action) {
switch (action.type) {
case 'INCREMENT':
return state + 1
case 'DECREMENT':
return state - 1
default:
return state
}
}
Using Redux
To use Redux, you create a store and give it a reducer:
import { createStore } from 'redux'
let store = createStore(counter)
You can then send actions to the store:
store.dispatch({ type: 'INCREMENT' })
And get the current state:
console.log(store.getState()) // 1
You can also listen for changes to the state:
store.subscribe(() => console.log(store.getState()))