Hey! I'm on a mission to make 100 React.js projects. Please follow my dev.to profile or my twitter for updates and feel free to reach out if you have questions. Thanks for your support!
Link to today's deployed app: Link
Link to the repo: github
This is my last project following Bob Ziroll's Scrimba React Bootcamp course, and it's my last project highlighting Redux, so it's going to be an easy, short one.
Counter apps are probably the most boring, easy thing to build but they do a great job highlighting a specific technology.
A pure Redux with react-redux
file with reducers and store might look something like this for a counter app (if you're lost I highly recommend you go back and check out any of my last 5 projects to get more background on Redux).
import redux, {createStore} from 'redux'
export function increment() {
return {
type: "INCREMENT"
}
}
export function decrement() {
return {
type: "DECREMENT"
}
}
function reducer(count = 0, action) {
switch(action.type) {
case "INCREMENT":
return count + 1
case "DECREMENT":
return count - 1
default:
return count
}
}
const store = createStore(reducer)
store.subscribe(() => console.log(store))
export default store
Now in the App component, we use JSX to create a simple counter UI. Rather than passing the reducers down via HOC to the App component through props we can now simply use the useSelector
hook to return the store
function App(props) {
const count = useSelector(state => state)
...
}
and instead of writing separate functions to subscribe to store changes, we can simply use the useDispatch()
hook. This auto-magically connects with our exported functions and store from the Redux file. Now we can remove any use of props from our component, and can go back to exporting App.
import React from "react"
import {useSelector,useDispatch} from "react-redux"
import {increment, decrement} from "./redux"
function App(props) {
const count = useSelector(state => state)
const dispatch = useDispatch()
return (
<div>
<header>
<h1>Counter using React Redux Hooks</h1>
<p>by{' '}
<a href='https://twitter.com/jwhubert91'>@jwhubert91</a>
</p>
</header>
<h2>{count}</h2>
<button onClick={() => dispatch(decrement())}>-</button>
<button onClick={() => dispatch(increment())}>+</button>
</div>
);
}
export default App
This greatly simplifies the look of our code in the App component and we don't have to mess around with HOCs any more, which is a blessing.
If you like projects like this and want to stay up to date with more, check out my Twitter @jwhubert91, I follow back! See you tomorrow for another project.
Top comments (0)