The thing is, you have to find a small analyze between function that return elements which takes arguments and functional component that returns elements which takes props.

Consider the below example :

 //here is the difference, when you use function, function takes arguments as it is.

  const  UpdateIcons = (products) => { 

  // if you use this as component props will be like products props will return the products object again, here you have to use {products} destructuring or products.propducts["One"]

  //like this const  UpdateIcons = ({products}) => { 

    if((products["One"]  === "A") && (products["Two"] === "B") && (products["Three"] === "C") ) {
      return <p>Conditional</p>
    }
    return <p>Show Always</p>
}

   class MyIssue extends Component {
     render() {
       const { products } = this.props;
        return ( 
          <div>
           {UpdateIcons(products)}  
           {/*passing arguments here products will be {"One": "A", "Two": "B"}*/}

           <UpdateIcons products={products}   /> 
           {/* passing props , props will be same as products */}
      </div>)
      }
    }

    class App extends Component {
      constructor() {
        super();
            this.state = {
                products: {
                   "One": "A",
                   "Two": "B",
                  "Three": "C"
                }
            };
     }

     render() {
        return <MyIssue products={this.state.products} />
     }
   }

working demo

Answer from Jayavel on Stack Overflow
Discussions

reactjs - React Function component setting state variable V/s using local variable - Stack Overflow
I have a functional component and want to update some state in that component (based on some context API object value i.e. I get via useContext) Now, I see 2 options; Using local variable Using se... More on stackoverflow.com
🌐 stackoverflow.com
reactjs - best way for local variables in functional component react native - Stack Overflow
I need a variable in the functional component that does not need to be state. There is no problem if I define it outside the component, but if it is inside the component, it will be reset in each w... More on stackoverflow.com
🌐 stackoverflow.com
React functional component reinitialises local functions and variables on re render (React Hooks)
So I have started using React hooks now. I have been experimenting with the API for some time now. i really like the idea of bringing the state to functional components. but there is this one thing... More on stackoverflow.com
🌐 stackoverflow.com
How to set local variable value as state
Please post your entire component. If using a class based implementation you would invoke setState() inside your click handler then use this.state.whatever. If it's a hook you would use the setter function you create with useState inside your functional component (or imported if it separated out into something like a shared hook) Edit: I am sorry misread your post. Can you still post the entire component? What is the shape on employ? More on reddit.com
🌐 r/reactjs
7
2
December 8, 2019
🌐
GitHub
github.com › facebook › react › issues › 15224
Using local variable name in function similar to state variable in Hooks · Issue #15224 · facebook/react
March 27, 2019 - Your bug will get fixed much faster if we can run your code and it doesn't have dependencies other than React. Paste the link to your JSFiddle (https://jsfiddle.net/Luktwrdm/) or CodeSandbox (https://codesandbox.io/s/new) example below: ... In below code, I am getting undefined error when accessing items.map, it gives items as undefined. Further analysis revealed that having local variable name the same as state variable in hooks was causing the issue.
Author   nitin15j
🌐
DEV Community
dev.to › carlosrafael22 › using-refs-in-react-functional-components-part-3-instance-like-variable-52n4
Using refs in React functional components (part 3) - instance-like variable - DEV Community
January 19, 2021 - This way, we see that with useRef we could have a property similar to an instance variable in a class but with a functional component thanks to the ref staying around over the lifetime of the component. However, keep in mind that this was an example just to illustrate this use of refs in React.
🌐
Stack Overflow
stackoverflow.com › questions › 69298903 › best-way-for-local-variables-in-functional-component-react-native
reactjs - best way for local variables in functional component react native - Stack Overflow
Thank you for your answer. Another case is true if I use useRef for the variable I mentioned? 2021-09-23T13:23:20.467Z+00:00 ... You can use the useRef hook. This will work, but as the name says, it is actually meant to hold a reference to something, for example a child component.
🌐
Chariot Solutions
chariotsolutions.com › home › functional react components, a primer, part 2
Functional React components, a primer, part 2 — Chariot Solutions
December 20, 2021 - Instead, we store it in a normal member variable of the class. We need the handle to clean up the timer, because it won't go away automatically when the component is unloaded (timers are managed at the window level, so you'll get all sorts of errors when the still-extant function is attempting to access destroyed objects).
🌐
Medium
rajeshnaroth.medium.com › component-state-management-in-react-functional-components-with-hooks-e7c412c05e71
State Management within React Functional Components with hooks | by Rajesh Naroth | Medium
June 25, 2020 - React functional components are plain JavaScript functions. It is not possible to persist state in local variables as these are initialized every time the function is evaluated.
Find elsewhere
Top answer
1 of 3
7

I had the same concerns as well when I first saw the proposal, but this was addressed in the React Docs Hooks Proposal FAQ:

Are Hooks slow because of creating functions in render?

No. In modern browsers, the raw performance of closures compared to classes doesn’t differ significantly except in extreme scenarios.

My takeaway is that although you have additional overhead now in the repeated declarations per render, you have additional wins elsewhere:

  • Hooks avoid a lot of the overhead that classes require, like the cost of creating class instances and binding event handlers in the constructor.

  • Idiomatic code using Hooks doesn’t need the deep component tree nesting that is prevalent in codebases that use higher-order components, render props, and context. With smaller component trees, React has less work to do.

Overall the benefits might be more than the downsides which makes hooks worth using.

2 of 3
2

You can always simplify the code to take functions out so that they aren't initialised always, by passing the required values as constants.

    import React, { useState } from "react";

    function doSomething (counterState, incrementCounterState){
       // does something and then calls incrementCounterState
       // with the updated state.
   }
    function Counter() {
      const [counterState,incrementCounterState] =  useCommontState(0); 

       return (
        <div>
          <p>{counterState}</p>
          <button onClick={incrementCounterState}>increase</button>
          ....
          .... // some jsx calling local scoped functions.
          ....
        </div>
        );
    }

    function increment(defaultValue, setState){
        setState(defaultValue + 1);
    }

    function useCommontState(defaultValue){
      var [state, setState] = useState(0);
      return [state, increment]
    }

    export default Counter;

Also in my opinion the function design being suggested in all the demos and docs is for people to get comfortable with it and then think about the re-initialization aspects. Also the cost that re-initialization would significanly be overpowered by the other benefits that it provides.

🌐
freeCodeCamp
freecodecamp.org › news › a-few-questions-on-functional-components
How to Use Functional Components in React
May 3, 2020 - Passing an update function allows you to access the current state value inside the updater. OK so increment() gets called with the current n state and it is used to compute the new state value. Let’s summarize what we found out. In React we can simply define a component using a function that returns an HTML-like syntax.
🌐
Medium
medium.com › @furkan-aydin › why-do-react-components-need-state-variables-908e98ca1e62
Why do React components need state variables? | by Furkan Aydın | Medium
September 2, 2024 - Function components can utilize local variables to store data. However, if the component want to adjust its appearance, the changes to function local variables alone are insufficient.
🌐
Robin Wieruch
robinwieruch.de › react-function-component
React Function Components - Robin Wieruch
December 23, 2024 - If you don’t care about the component name by defining the variable, you can keep it as Anonymous Function Component when using a default export on the Function Component: ... import React from 'react'; import Headline from './Headline.js'; export default () => { const greeting = 'Hello Function Component!'; return <Headline value={greeting} />; };
🌐
React
legacy.reactjs.org › docs › hooks-state.html
Using the State Hook – React
Line 1: We import the useState Hook from React. It lets us keep local state in a function component. Line 4: Inside the Example component, we declare a new state variable by calling the useState Hook. It returns a pair of values, to which we give names. We’re calling our variable count because it holds the number of button clicks.
🌐
Pluralsight
pluralsight.com › tech insights & how-to guides › tech guides & tutorials
How to Use Variables within Classes | Pluralsight
March 19, 2020 - import React, { Component } from "react"; import { render } from "react-dom"; class App extends Component { // Declaring static variable static num1 = 3.1416; constructor() { super(); } render() { return ( <div> <div>Accessing local static number variable : {this.num1}</div> </div> ); } } render(<App />, document.getElementById("root"));
🌐
React
react.dev › learn › state-a-components-memory
State: A Component's Memory – React
This is what makes state different from regular variables that you might declare at the top of your module. State is not tied to a particular function call or a place in the code, but it’s “local” to the specific place on the screen. You rendered two <Gallery /> components, so their state is stored separately.
🌐
Reddit
reddit.com › r/reactjs › how to set local variable value as state
r/reactjs on Reddit: How to set local variable value as state
December 8, 2019 -

Hey, I'm working on this code as side project. Mapping employ gives me data._id but when I update state in render it gives Uncaught Invariant Violation: Too many re-renders. React limits the number of renders to prevent an infinite loop and I can't set state outside render because it is in local scope. So, I want to update state with data._id when edit button is clicked.

I'm using hooks for this and setId is the useState setter.

                  {employ.map(data => (
                    <EuiFlexGroup gutterSize="l" > 
          
                      <EuiFlexItem className="items_menu-item_title">
                        <EuiCard
                          title={data.company}
                          description={data.position}
                        />
                        <EuiButton
                          color="danger"
                          size="s"
                          className="btn btn-outline-danger"
                        >
                          Delete
                          </EuiButton>
                        <EuiButton
                          color="danger"
                          size="s"
                          className="btn btn-outline-success"
                          onClick={formedit}
                          onClick={setId(data._id)}
                        >
                          Edit
                        </EuiButton>
                      </EuiFlexItem>
                      <br />
                    </EuiFlexGroup>
                  ))}
🌐
Reddit
reddit.com › r/reactjs › useref vs local let variable
r/reactjs on Reddit: useRef vs local let variable
April 8, 2022 -

Is there some benefit to using useRef vs a local variable, especially in case where it's not intended to be shared between multiple instances of the same component.

In this example, it's being used to keep track of a timer that's perhaps cleared and reassigned with new timers in other places in the component.

Will timer2 be reassigned to null when stateItem changes and triggers a render?

const myComponent = ({stateItem}) => {
const timer1 = useRef(null);
let timer2 = null;
useEffect(() => {
timer1.current = setTimeout(()=> { }, 1000);
timer2 = setTimeout(() => { }, 10000);
return () => {
clearTimeout(timer1.current);
clearTimeout(timer2);
};
// other component stuff
}, [stateItem]);

🌐
Reddit
reddit.com › r/react › best way to go about non-changing variables in functional components?
r/react on Reddit: Best way to go about non-changing variables in functional components?
October 15, 2021 -

Wondering what's the best way to do this. Let's say we're making a post component, and for each post component there are things that will change (likes, comments) and things that will never change (url, image). I'm currently getting all my data through an api call with useEffect and inside the useEffect hook I use my state hooks to set my variables that will be updating throughout the duration of the post. I could put url and image in a useState hook and just never change it again, but is that the best way to do it? I tried doing let url = data.url inside my useEffect but I don't think that was working correctly