React best practices and patterns to reduce code
Tags: react, redux, reactnative, javascript
Published: 2022-03-15 15:57:27

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/67vywjv6ia1q801godxy.png)
 


I have been working with React.js from the past couple of years and have been using it for several 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.

[![React best practices and patterns to reduce code](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9qfo68lckofw16nfgp16.png)](https://www.youtube.com/watch?v=Y85X4PiuuTM)


### 1. Create custom hooks for redux actions and dispatches
I’m not a fan of using redux, but I’ve been using it for several 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.

I've created another article about state management [3 steps to create custom state management library](https://dev.to/devsmitra/3-steps-to-create-custom-state-management-library-with-react-hooks-and-context-api-1bfh)

```javascript
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 Component**
```javascript
const { 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 hook to get any info from redux._


### 2. Use object instead of switch inside the reducer

This is not a good idea if you have a lot of cases to handle. You can use an object literal as an alternative to switch statements. The object literal is more readable and easier to maintain.
```javascript
const actionMap = {
  INCREMENT:(state, act) => ({...state, count: state.count + 1 }),
  DECREMENT: (state, act) => ({...state, count: state.count - 1 }),
}

const reducer = (state, action) => {
  const handler = actionMap[action.type];
  return handler ? handler(state, action) : state;
};
```

_**NOTE:** The map variable must be declared outside the dispatch context otherwise it will always be re-evaluated.
A switch can be implemented using a tree which makes it O(log n) in the map(object) searching is O(1)._

### 3. Create a hook for REST calls

you can use the browser fetch API and create your hook and avoid some repetition of code. like get data from API update in state and render.

```javascript
const useFetch = (input, { auto, ...init }) => {
  const [result, setResult] = useState([null, null, true]);
  
  const fetcher = useCallback(
    (query, config) =>
      fetch(query, config)
        .then((res) => res.json())
        .then((data) => setResult([null, data, false]))
        .catch((err) => setResult([err, null, false])),
    [input, init]
  );

  useEffect(() => {
    if (auto) fetcher(input, init);
  }, []); // if you want to fetch data only once, do this.
  
  return [...result, fetcher];
  //fetcher(refetch) function or can be used for post api call
};

```

**Inside Component**
```javascript
const Users = () => {
  const [err, users, loading, refetch] = useFetch(`/api/users`, {auto:true});

  const onClick = () => refetch(...);

  return (
    <div>
      {users.map((user) => <User key={user.id} user={user} />)}
    </div>
  );
}

```

_**NOTE:** It’s similar to react-query/useSWR, both the libraries have much more to offer. you can use these libraries, but if you have restrictions on your project you can go ahead with this approach avoid some extra code._

### 4. Code Splitting
use React.lazy, It is a very powerful tool that allows you to load components only when they are needed. The React.lazy function lets you render a dynamic import as a regular component.

**A good place to start is with routes**. When you go with the traditional approach, you have to load both components before rendering them, but this is not a good approach, because it will take extra time to load all components. Even though we are not showing the component.

We can use **react.lazy** to load the components asynchronously. So when you are at the first(Home) page, you can load the first component and when you are at the second(About) page, you can load the second component. This way we can avoid unnecessary loading of components.

```javascript
const Home = React.lazy(() => import('./Home'));
const About = React.lazy(() => import('./About'));
function MyComponent() {
  return (
    <Suspense fallback={<div>Loading...</div>}>
      <Route path="/home" component={Home} />
      <Route path="/about" component={About} />
    </Suspense>
  );
}
```

_**NOTE:** This is a very simple use case but what if we have 100’s of routes and components. You will see a huge difference in the performance._


**Reference:**
Code-Splitting — [React (reactjs.org)](https://reactjs.org/docs/code-splitting.html)

Thank you for reading 😊

Got any questions or additional? please leave a comment.

---
### Must Read If you haven't

{% link https://dev.to/devsmitra/no-more-redux-action-creators-functions-30j %}

{% link https://dev.to/devsmitra/how-to-cancel-javascript-api-request-with-abortcontroller-36cm %}

{% link https://dev.to/devsmitra/13-typescript-utility-a-cheat-sheet-for-developer-ab3 %}

{% link https://dev.to/devsmitra/how-to-solve-rest-api-routing-problem-with-decorators-5b3n %}

### Catch me on
{% user devsmitra %}
<p>
{% cta https://www.youtube.com/@devsmitra?sub_confirmation=1 %} Youtube {% endcta %}
{% cta https://github.com/devsmitra %} Github {% endcta %}
{% cta https://www.linkedin.com/in/rahul-sharma-18b8b374 %} LinkedIn {% endcta %}
{% cta https://devsmitra.medium.com %} Medium {% endcta %}
{% cta https://stackblitz.com/@devsmitra %} Stackblitz {% endcta %} {% cta https://devsmitra.hashnode.dev %} Hashnode {% endcta %}
{% cta https://hackernoon.com/u/devsmitra %} HackerNoon {% endcta %}
</p>