Awesome React Resources
Awesome React Components
Super huge collection of react components!
Functional React
useState
useHooks
useReducer
If you find yourself having to deal with multiple state transitions, use useReducer
instead. It's way harder to manage it with useState()
. Here's an example:
const [todos, setTodos] = useState([]);
// deal with adding todo
setTodos(...todos, ...[{id: 1, content: "a single todo"}]);
// deleting a todo
setTodos(todos.filter((todo) => todo.id !== targetTodo.id)
// 20 other things you might want to do with a todo list
With useReducer, you're bundling all the ways the state will be affected in a single method. It's significantly more manageable. For example...
const todosReducer = (state, action) => {
switch(action.type) {
case "INSERT":
return [...state, ...action.todo];
case "DELETE":
return state.filter((todo) => todo.id !== action.todo.id);
default:
// do something else
}
}
const initialTodos = []; // empty list of todos
// instantiating the list of todos and binding it to the reducer we created
const [todos, dispatch] = useReducer(todosReducer, initialTodos);
// using the dispatch method we created above to modify our todos list
dispatch({
type: "INSERT",
todo: { id: 3, content: "todo 3" }
});
It's actually not that hard once you walk through the steps one-by-one. Initially, I was intimidated by these new React concepts. But now that I've seen how much simpler it is, it can be a powerful abstraction to deal with complex states and state transitions.
Redux Thunk
What's a thunk?
It's another way of saying a function that returns a function. To execute the function inside the wrapper function, you have to do something like
your_function()()
// notice that additional ()?
What's a redux action?
Let's take a look at how you would create one first.
{
type: "ADD_TODO",
text: "This is a todo"
}
Notice that it's a hash / dictionary. In other words, it's a javascript object.