Created
January 23, 2022 04:12
-
-
Save ynwd/60ecc259fde9a7b5e2e2d51e1fe4788e to your computer and use it in GitHub Desktop.
react redux with initial state
This file contains 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
import React from 'react' | |
import { Provider, useSelector, useDispatch } from 'react-redux' | |
import { createStore } from 'redux' | |
function Counter() { | |
const count = useSelector(state => state.count) | |
const dispatch = useDispatch() | |
const action = { | |
type: "ADD", | |
count: 1 | |
} | |
return ( | |
<div> | |
<p>You clicked {count} times</p> | |
<button onClick={() => dispatch(action)}> | |
Click me | |
</button> | |
</div> | |
) | |
} | |
function reducer(state, action) { | |
if (action.type === "ADD") { | |
return { | |
count: state.count + 1 | |
} | |
} | |
return { | |
count: 0 | |
} | |
} | |
const initialState = { | |
count: 0 | |
} | |
const store = createStore(reducer, initialState) | |
function App() { | |
return ( | |
<Provider store={store}> | |
<Counter /> | |
</Provider> | |
) | |
} | |
export default App |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment