Skip to content

Instantly share code, notes, and snippets.

@Herve07h22
Created May 28, 2021 12:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Herve07h22/17e88ee412d58c0abeb4b55372e8c89f to your computer and use it in GitHub Desktop.
Save Herve07h22/17e88ee412d58c0abeb4b55372e8c89f to your computer and use it in GitHub Desktop.
Pourquoi je préfère les hooks
// Avec readux toolkit :
import { createSlice } from '@reduxjs/toolkit'
export const counterSlice = createSlice({
name: 'counter',
initialState: {
value: 0,
},
reducers: {
increment: (state) => {
// Redux Toolkit allows us to write "mutating" logic in reducers. It
// doesn't actually mutate the state because it uses the Immer library,
// which detects changes to a "draft state" and produces a brand new
// immutable state based off those changes
state.value += 1
},
decrement: (state) => {
state.value -= 1
},
incrementByAmount: (state, action) => {
state.value += action.payload
},
},
})
// Action creators are generated for each case reducer function
export const { increment, decrement, incrementByAmount } = counterSlice.actions
export default counterSlice.reducer
export const useCounter = (dependencies) => {
const [counter, setCounter] = useState(0)
const increment = () => setCounter(value => value+1)
const decrement = () => setCounter(value => value-1)
const incrementByAmount = (amount) => setCounter(value => value+amount)
return { counter, increment, decrement, incrementByAmount}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment