website securuty

How to write helper functions in React

Helper functions are small pieces of code that perform a specific task and can be reused throughout your application. They can help you write cleaner, more modular, and more maintainable code in React. In this blog post, I will show you how to write helper functions in React and some examples of common use cases.

There are two main ways to write helper functions in React: as regular JavaScript functions or as custom hooks. Let’s see the pros and cons of each approach and how to use them.

Regular JavaScript functions

Regular JavaScript functions are the simplest way to write helper functions in React. They are just plain functions that take some input and return some output. You can define them anywhere in your code, either inside or outside of your React components, and import them as needed. For example, you can write a helper function that capitalizes the first letter of a string like this:

// helper.js
export function capitalize(str) {
  return str.charAt(0).toUpperCase() + str.slice(1);
}

And then use it in your React component like this:

// App.js
import React from 'react';
import { capitalize } from './helper';

function App() {
  const name = 'john';
  return <div>Hello, {capitalize(name)}!</div>;
}

export default App;

The advantages of using regular JavaScript functions as helper functions are:

  • They are easy to write and understand.
  • They are pure and have no side effects.
  • They are testable and reusable.
  • They can be used in any JavaScript project, not just React.

The disadvantages of using regular JavaScript functions as helper functions are:

  • They cannot access the React state or lifecycle methods directly.
  • They cannot use other React hooks inside them.
  • They may cause unnecessary re-rendering if they are defined inside the component and passed as props to other components.

Custom hooks

Custom hooks are a special kind of helper functions that use the use prefix and follow the rules of hooks. They can access the React state and lifecycle methods, as well as use other React hooks inside them. They can also return any value, not just a single one. You can write a custom hook like this:

// useFetch.js
import { useState, useEffect } from 'react';

export function useFetch(url) {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    fetch(url)
      .then((response) => {
        if (!response.ok) {
          throw new Error(response.statusText);
        }
        return response.json();
      })
      .then((data) => {
        setData(data);
        setLoading(false);
      })
      .catch((error) => {
        setError(error);
        setLoading(false);
      });
  }, [url]);

  return { data, loading, error };
}

And then use it in your React component like this:

// App.js
import React from 'react';
import { useFetch } from './useFetch';

function App() {
  const { data, loading, error } = useFetch('https://jsonplaceholder.typicode.com/users');

  if (loading) {
    return <div>Loading...</div>;
  }

  if (error) {
    return <div>Error: {error.message}</div>;
  }

  return (
    <div>
      <h1>Users</h1>
      <ul>
        {data.map((user) => (
          <li key={user.id}>{user.name}</li>
        ))}
      </ul>
    </div>
  );
}

export default App;

The advantages of using custom hooks as helper functions are:

  • They can access the React state and lifecycle methods directly.
  • They can use other React hooks inside them.
  • They can return multiple values and share stateful logic between components.
  • They can avoid unnecessary re-rendering by using memoization techniques.

The disadvantages of using custom hooks as helper functions are:

  • They are more complex and require more boilerplate code.
  • They are specific to React and cannot be used in other JavaScript projects.
  • They may cause bugs if they do not follow the rules of hooks.

Examples of helper functions in React

Here are some examples of common helper functions that you can write in React using either regular JavaScript functions or custom hooks.

Formatting dates

You can write a helper function that formats a date object into a human-readable string using the built-in Date methods or a library like moment.js. For example, you can write a helper function that returns the date in the format MMM DD, YYYY like this:

// helper.js
export function formatDate(date) {
  const monthNames = [
    'Jan',
    'Feb',
    'Mar',
    'Apr',
    'May',
    'Jun',
    'Jul',
    'Aug',
    'Sep',
    'Oct',
    'Nov',
    'Dec',
  ];
  const month = monthNames[date.getMonth()];
  const day = date.getDate();
  const year = date.getFullYear();
  return `${month} ${day}, ${year}`;
}

Or you can use moment.js like this:

// helper.js
import moment from 'moment';

export function formatDate(date) {
  return moment(date).format('MMM DD, YYYY');
}

And then use it in your React component like this:

// App.js
import React from 'react';
import { formatDate } from './helper';

function App() {
  const date = new Date();
  return <div>Today is {formatDate(date)}</div>;
}

export default App;

Validating forms

You can write a helper function that validates the input values of a form and returns an object with the error messages for each field. You can use regular expressions, custom rules, or a library like yup to perform the validation. For example, you can write a helper function that validates a simple login form like this:

// helper.js
export function validateForm(values) {
  const errors = {};
  if (!values.email) {
    errors.email = 'Email is required';
  } else if (!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i.test(values.email)) {
    errors.email = 'Email is invalid';
  }
  if (!values.password) {
    errors.password = 'Password is required';
  } else if (values.password.length < 6) {
    errors.password = 'Password must be at least 6 characters';
  }
  return errors;
}

Or you can use yup like this:

// helper.js
import * as yup from 'yup';

export const schema = yup.object().shape({
  email: yup
    .string()
    .email('Email is invalid')
    .required('Email is required'),
  password: yup
    .string()
    .min(6, 'Password must be at least 6 characters')
    .required('Password is required'),
});

And then use it in your React component like this:

// App.js
import React, { useState } from 'react';
import { validateForm } from './helper'; // or import { schema } from './helper';

function App() {
  const [values, setValues] = useState({ email: '', password: '' });
  const [errors, setErrors] = useState({});

  const handleChange = (e) => {
    const { name, value } = e.target;
    setValues({ ...values, [name]: value });
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    // const errors = validateForm(values); // or const errors = await schema.validate(values, { abortEarly: false });
    setErrors(errors);
    if (Object.keys(errors).length === 0) {
      // submit the form
    }
  };

  return (
    <form onSubmit={handleSubmit}>
      <div>
        <label htmlFor="email">Email</label>
        <input
          id="email"
          name="email"
          type="email"
          value={values.email}
          onChange={handleChange}
        />
        {errors.email && <span>{errors.email}</span>}
      </div>
      <div>
        <label htmlFor="password">Password</label>
        <input
          id="password"
          name="password"
          type="password"
          value={values.password}
          onChange={handleChange}
        />
        {errors.password && <span>{errors.password}</span>}
      </div>
      <button type="submit">Login</button>
    </form>
  );
}

export default App;

Conclusion

Helper functions are a great way to write cleaner, more modular, and more maintainable code in React. You can write them as regular JavaScript functions or as custom hooks, depending on your needs and preferences. In this blog post, I showed you how to write helper functions in React and some examples of common use cases. I hope you found it helpful and learned something new. Happy coding!

Leave a Comment

Your email address will not be published. Required fields are marked *