Member-only story
React best practices and patterns to reduce code
I have been working with React.js for the past 4 to 5 years and have been using it for a number of different projects. While working on different projects I’ve found some common patterns I would like to share in this blog post. Without further ado, Let’s get started.
1. Create custom hooks for redux actions and dispatches
I’m not a fan of using redux, but I’ve been using it for a number of different projects. I’ve found that redux-thunk is used in almost all the projects I’ve worked on. I found that is more of a boilerplate code.
Let’s take an example of a redux-thunk project.
function fetchUser(id) {
return (dispatch, getState, { api, otherValue }) => {
return fetch(`/api/user/${id}`)
.then(res => res.json())
.then(user => dispatch({ type: ‘FETCH_USER’, payload: user }))
}
}function fetchUsers() {
return (dispatch, getState, { api, otherValue }) => {
return fetch(`/api/users`)
.then(res => res.json())
.then(user => dispatch({ type:‘FETCH_USERS’, payload: user }))
}
}
Create a custom hook for all user actions.
const useUser = () => {
const dispatch = useDispatch();
const state = useSelector(); // get auth info or something const fetchUser = (id) => {
return fetch(`/api/user/${id}`).then((res) => res.json())
.then((user) => dispatch({type: "FETCH_USER",payload:user}));
}; const fetchUsers = () => {
return fetch('/api/users').then((res) => res.json())
.then((user) => dispatch({type:"FETCH_USERS",payload: user}));
}; return { fetchUser, fetchUsers };
}
// Inside Componentconst { fetchUser } = useUser();
useEffect(() => fetchUser(1), [])
NOTE: As you can see here I don’t have to create multiple functions for all redux actions. We can also use the useSelector…