Created
May 28, 2021 12:40
-
-
Save Herve07h22/17e88ee412d58c0abeb4b55372e8c89f to your computer and use it in GitHub Desktop.
Pourquoi je préfère les hooks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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