Skip to content

Instantly share code, notes, and snippets.

@rockiger
Created February 19, 2021 08:47
Show Gist options
  • Save rockiger/de8d03d71b684d7492491c237d0a7ceb to your computer and use it in GitHub Desktop.
Save rockiger/de8d03d71b684d7492491c237d0a7ceb to your computer and use it in GitHub Desktop.
import React from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { createSlice } from '@reduxjs/toolkit'
// 1) Create state and actions/reducers
const counterSlice = createSlice({
name: 'counter',
initialState: {
value: 0,
},
reducers: {
incremented: (state) => {
return {value: state.value + 1};
},
decremented: (state) => {
return { value: state.value - 1 };
},
},
})
export const { incremented, decremented } = counterSlice.actions
// 2) select and dispatch
export const Count = () => {
const count = useSelector(state => state.counter.count)
const dispatch = useDispatch()
return (
<main>
<div>Count: {count}</div>
<button onClick={() => dispatch(incremented())}>Decrement</button>
<button onClick={() => dispatch(decremented())}>Increment</button>
</main>
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment