If you put the helper function inside the component function, everytime the component function gets executed, it will create a new instance of the helper function and after the function was executed the instance possibly gets garbage collected. So typically I would put it outside.

Of course there are exceptions, if you use an arrow function, you might need the lexical scope and therefor put it inside the component function, but if it's a pure function, I would say it should go outside.

Answer from gwildu on Stack Overflow
🌐
Reddit
reddit.com › r/reactjs › where to put helper functions in a react component?
r/reactjs on Reddit: Where to put helper functions in a React component?
April 8, 2016 -

So, as an example, I have a function that simply maps over an input array and returns an array. This function does not interact with the UI or call any other functions at all.

Where should this function go? Should I declare it within the Component? Should I make a separate function() declaration outside the Component at the bottom of the file?

If it's a function that is used in many files I would probably create a helper file to use it, but what if it's specific to this Component?

Just wondering what best practice is and why.

🌐
DEV Community
dev.to › anilsingh › create-use-helper-functions-react-component-1jhj
Create & Use Helper Functions | React Component - DEV Community
January 16, 2024 - Also, you can achieve code reusability by using these functions. In the blow example, we have to create a helper class and use to it. ... import React from 'react'; import { plus, minus } from './Helpers' class CalculatorComponents extends React.Component { constructor(props){ super(props); this.yourClickFunction=this.yourClickFunction.bind(this); } yourClickFunction(x, y){ console.log(this.plus(x, y)); //Output will be (10, 20) => 30 } render() { return ( <div > <h4 >React Helper functions</ h4> < button onClick={this.yourClickFunction(10, 20)}>Click..</ button > </div > ); } } export default CalculatorComponents;
Discussions

reactjs - Helpers in stateless functional components - Stack Overflow
With the introduction of Stateless functional components in react we have multiple ways to add helper methods to our component. What is the defined standard practice in regards to helper functions?... More on stackoverflow.com
🌐 stackoverflow.com
Initialise helper class in a react functional component
The class methods which are passed as args from the functional component, are kept 'in memory' and doest not reflect the updated state. I can reinitialise on state changes but wish to avoid it. const More on stackoverflow.com
🌐 stackoverflow.com
Does having a lot of inner 'helper' functions inside a functional stateless react component will result in worse performance
His argument was that every time that my component is rendered all the 'inner member functions' are created again and that might result in worse performance. I was under the impression that React team wanted people to ditch classes whenever possible. Does having a lot of helper functions inside ... More on stackoverflow.com
🌐 stackoverflow.com
reactjs - How to create helper file full of functions in react native? - Stack Overflow
Not sure if the method is already outdated or not as RN is evolving very fast. How to create global helper function in react native? I am new to React Native. What I want to do is to create a js file full of many reusable functions and then import it in components and call it from there. More on stackoverflow.com
🌐 stackoverflow.com
🌐
Ncoughlin
ncoughlin.com › posts › react-component-helper-functions
React: Component Helper Functions | Nicholas Coughlin
February 1, 2021 - In addition we can actually simplify this render function more by pulling out the click event handler into a helper function like so. ... import React, { Component } from "react"; import { connect } from "react-redux"; /* Redux Actions */ import { toggleMenu } from "../actions/index"; /* Icons */ import ChevronLeft from "./icons/ChevronLeft"; import ChevronRight from "./icons/ChevronRight"; class ContentMenuCollapse extends Component { /* Helper Functions */ /* click handler */ onCollapseClick() { /* toggle menu redux action */ return () => this.props.toggleMenu(this.props.collapse); } /* chan
🌐
Stack Overflow
stackoverflow.com › questions › 67887965 › initialise-helper-class-in-a-react-functional-component
Initialise helper class in a react functional component
const MyFunctional = (props) => { const [state, setState] = useState(0); const latestStateRef = useLatest(state); const helper = useRef(); useEffect(() => { helper.current = new HelperClass(onSuccess, onFailure); }, []); const onSuccess = (result) => { console.log(latestStateRef.current); }; const onFailure = (error) => { console.log(latestStateRef.current); }; };
Find elsewhere
🌐
Ben Ilegbodu
benmvp.com › blog › helper-functions-react-useeffect-hook
Helper functions in the React useEffect hook | Ben Ilegbodu
October 10, 2020 - This time instead of the error being on the useEffect dependencies list, it’s about the hideMessage helper function itself. Because it’s being declared within the React component function, there’s going to be a new version of it every time the component re-renders.
🌐
DhiWise
dhiwise.com › post › a-guide-to-leveraging-react-helper-functions-for-development
React Helper Functions: Create, Integrate and Optimize Code
October 3, 2024 - The lifecycle of a helper function in a React project typically involves the following stages: Creation: The function is written to address a specific need or to abstract away common logic. Integration: The function is imported and used in one or more React components.
🌐
LinkedIn
linkedin.com › pulse › react-best-practices-rashi-dhar
React Best Practices
August 27, 2021 - // 👎 Class components are verbose ... ​={handleClick}>Increment</button> </div> ) } Place helper functions into utils js file, so that they can be used across the React components....
🌐
Code-sample
code-sample.com › 2019 › 11 › react-create-use-helper-functions.html
React Create & Use Helper Functions | React Component
November 28, 2019 - Labels: Creating Reusable Helper Functions in React.js React create helper functions React export function from class React helper methods use helper functions in a React component
🌐
Reddit
reddit.com › r/reactjs › placing helper functions outside of components?
r/reactjs on Reddit: Placing helper functions outside of components?
August 10, 2021 -

So whenever a functional component re-renders (state changes), everything in the component gets re-created. So with that in mind... if there's a helper function that's pure, should we always put it outside of the component (not inside component's scope)? Is there actual performance benefit in not having this function always recreated on render? I always thought it was for readability. Example below would only re-render if the parent component re-renders but that's beside the point:

const sum = (a, b) => a + b;

const addComponent = ({num1, num2}) => {

return <div>{sum(num1, num2)}</div>

}

vs

const addComponent = ({num1, num2}) => {

const sum = (a, b) => a + b;

return <div>{sum(num1, num2)}</div>

}

🌐
npm
npmjs.com › package › react-component-helpers
react-component-helpers - npm
April 13, 2016 - Sign UpSign In · 0.0.7 • Public • Published 9 years ago · Readme · Code Beta · 0 Dependencies · 2 Dependents · 6 Versions · A collection of helper methods to remove boilerplate code from your React Components.
      » npm install react-component-helpers
    
Published   Apr 13, 2016
Version   0.0.7
Author   Calvin Froedge
🌐
Medium
medium.com › @tacomanator › react-helper-order-components-ab657aa1d9eb
React helper-order components 💪🏼 | by Drew Goodwin | Medium
May 6, 2017 - import React from “react”: import { Button } from “somewhere”;const CoolButton = props => ( <Button cool="true" {...props} /> );export default CoolButton; To peek at the props you change the function: const CoolButton = props => { console.log(props); return <Button cool="true" {...props} />; } With a helper-order component, however, the footprint is smaller (the change is temporary so require is used inline): export default require("hocs/logProps")(CoolButton); For reference, here is a very basic implementation of logProps: import React from "react";export default WrappedComponent => props => { console.log(WrappedComponent.name, props) return <WrappedComponent {...props} />; }; If already using other higher-order components, especially with a utility like recompose, using logProps might require even bigger changes.
Top answer
1 of 1
4

You have to use the useFetch hook in the main render function. You can't use it inside of another function. You'll need to adjust your useFetch to work separately.

Here's an example of how to do that. In this case, I'm making the useFetch refetch when the url or options change

helper.js

import { useState, useEffect } from 'react';

export const GH_BASE_URL = 'https://api.github.com/';

export const useFetch = (url, options) => {
  const [response, setResponse] = useState(null);
  const [error, setError] = useState(null);
  const [isLoading, setIsLoading] = useState(false);

  useEffect(() => {
    // Set up aborting
    const controller = new AbortController();
    const signal = controller.signal;
    const fetchData = async () => {
      setIsLoading(true);

      try {
        const res = await fetch(url, { ...options, signal });
        const json = await res.json();
        setResponse(json);
        setIsLoading(false);
      } catch (error) {
        // AbortError means that the fetch was cancelled, so no need to set error
        if (error.name !== 'AbortError') {
          setError(error);
        }
      }
    };

    if (url) {
      fetchData();
    }
    // Clear up the fetch by aborting the old one
    // That way there's no race condition issues here
    return () => {
      controller.abort();
    };
    // url and options need to be in the effect's dependency array
  }, [url, options]);

  return { response, error, isLoading };
};

Header.js

import React, { useState } from 'react';
import { useFetch, GH_BASE_URL } from '../helpers';

const REPO_SEARCH_URL = `${GH_BASE_URL}/search/repositories?q=`;

function Header(props) {
  const [searchValue, setSearchValue] = useState('');

  
  function handleChange(event) {
    this.setState({ searchValue: event.target.value });
  }

  // Instead of using the search directly, wait for submission to set it
  const [searchDebounce,setSearchDebounce] = useState('');
  
  async function handleSearch(event) {
    event.preventDefault();
    setSearchDebounce(searchValue);
  }
  // If you want to include the options, you should memoize it, otherwise the fetch will re-run on every render and it'll cause an infinite loop.
  // This will refetch everytime searchDebounce is changed
  const { response, error, isLoading } = useFetch(
    searchDebounce?`${REPO_SEARCH_URL}${searchDebounce}`:''
  );

  return (
    <header>
      <form onSubmit={handleSearch} className="container">
        <input
          value={searchValue}
          onChange={handleChange}
          className="search-input"
          placeholder="Search a repository"
        ></input>
      </form>
    </header>
  );
}

export default Header;

If you want to run a function whenever the response changes, you could use an effect:

  useEffect(() => {
    if (error || isLoading) {
      return;
    }
    // Destructure this to prevent a deps issue on the hooks eslint config
    const { responseChanged } = props;
    responseChanged(response);
  }, [response, isLoading, error, props.responseChanged]);

🌐
freeCodeCamp
freecodecamp.org › news › helper-functions-in-react
How to Write Helper Functions in React
November 2, 2023 - In this section, we'll discuss strategies for effectively organizing your helper functions within your React project. Proper organization makes your codebase more manageable as it scales. Organizing your helper functions is crucial to keep your project clean and maintainable. Consider creating a dedicated directory for your helper functions. You can structure it based on functionality, where related functions are grouped together. src/ |-- components/ |-- helperFunctions/ |-- dataManipulation/ |-- formatDate.js |-- calculateTotalPrice.js |-- validation/ |-- validateEmail.js |-- validatePassword.js