Redux is a state management library. It implements a Flux pattern of handling the data and its primary feature is the reducing of the previous state to produce the next state.
Flux is an architecture pattern to handle data fetching. It splits data fetching into separate layers, making them predictable, but also embeds a "model" and "controller" parts of traditional MVC into modern applications.
- Store. A single source of truth for the state.
- Action. A function that describes a change in a state. May contain next data.
- Dispatcher. A function that executes an Action.
- View. Component(s) that depend on the Store.
Primitive example.
const store = {
likes: 0
}
const addLike = () => {
return {
type: 'ADD_LIKE',
amount: 1
}
}
const dispatcher = () => {
_dispatch(addLike())
}
const Component = () => {
return <p>Likes: {store.likes}</p>
}
What problems do you see with such approach? Is there anything missing?
npm install redux react-redux
// src/store/index.js
import { createStore } from 'redux'
const initialState = {
likes: 0
}
function likesReducer(state = initialState, action) {
switch (action.type) {
case 'ADD_LIKE':
return state.likes + action.amount
default:
return state
}
}
export default createStore(likesReducer)
import React from 'react'
import { useSelector } from 'react-redux'
const Component = () => {
const likesCount = useSelector(state => state.likes)
return <p>Likes: {likesCount}</p>
}
// src/store/likes-actions.js
export const addLike = () => ({
type: 'ADD_LIKE',
amount: 1
})
import React from 'react'
import { useSelector, useDispatcher } from 'react-redux'
import { addLike } from './store/likes-actions'
const Component = () => {
const dispatch = useDispatcher()
const likesCount = useSelector(state => state.likes)
return (
<div>
<p>Likes: {likesCount}</p>
<button onClick={() => dispatch(addLike())}>Add like</button>
</div>
)
}