Skip to content

Instantly share code, notes, and snippets.

@cassidoo
Last active November 25, 2025 14:51
Show Gist options
  • Select an option

  • Save cassidoo/f3e5a01815a647b23183ffe5c7021aa3 to your computer and use it in GitHub Desktop.

Select an option

Save cassidoo/f3e5a01815a647b23183ffe5c7021aa3 to your computer and use it in GitHub Desktop.
let array = [1, 2, 3, 4, 5];
let add = (x, y) => x + y;
let sum = array.reduce(add, 0);
// This will do:
// 0 + 1
// 1 + 2
// 3 + 3
// 6 + 4
// 10 + 5
const initialState = { count: 0, user: {} }
const actions = [
{ type: 'ADD', by: 2 },
{ type: 'MINUS', by: 4 },
{ type: 'LOG_IN', name: 'fish' }
];
function reducer(state, action) {
if (action.type === 'ADD') {
return { ...state, count: state.count + action.by };
} else if (action.type === 'MINUS') {
return { ...state, count: state.count - action.by };
} else if (action.type === 'LOG_IN') {
return { ...state, user: { name: action.name } };
}
}
console.log(actions.reduce(reducer, initialState)); // count is -2, user's name is fish
@cassidoo
Copy link
Author

let [state, dispatch] = useReducer(
  (state, action) => { ... },
  { count: 0, user: {} }
) 

@cassidoo
Copy link
Author

let [count, setCount] = useState(0);

setCount(5);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment