scrimba
Reusable React
Reducers
Custom Hooks
Go Pro!Bootcamp

Bootcamp

Study group

Collaborate with peers in your dedicated #study-group channel.

Code reviews

Submit projects for review using the /review command in your #code-reviews channel

AboutCommentsNotes
Custom Hooks
Expand for more info
index.js
run
preview
console
import React, { useReducer } from 'react';
import ReactDOM from 'react-dom';

function useState(initialValue) {
let [state, dispatch] = useReducer((state, action) => {
return action
}, initialValue)

return [state, dispatch]
}

const App = () => {
const [state, dispatch] = useReducer((state, action) => {
switch(action.type) {
case 'INCREMENT': {
return { ...state, count: state.count + 1 }
}
case 'DECREMENT': {
return { ...state, count: state.count - 1 }
}
default: {
return state
}
}
}, {
count: 0
})

let { count } = state

const add = () => {
dispatch({ type: 'INCREMENT' })
}

const subtract = () => {
if (count > 0) {
dispatch({ type: 'DECREMENT' })
}
}

return (
<section>
<h2>Counter: The Most Novel Example I Could Come Up With</h2>
<div className="counter">
<button onClick={subtract}>-</button>
<div>{count}</div>
<button onClick={add}>+</button>
</div>
</section>
)
}

ReactDOM.render(<App />, document.getElementById('root'));
Console
/index.html?
-4:29