Home > Net >  Is there a higher order function to avoid fire on render?
Is there a higher order function to avoid fire on render?

Time:10-12

I have a function

const onClick = (param) => console.log(param)

and need to use it like:

<Button onClick={onClick(value)} />

But it fires on render, how I can change function into higher order function to use it like that?

CodePudding user response:

Not sure where value is coming from but like this?

<Button onClick={() => onClick(value)} />

CodePudding user response:

You can try this

import React from 'react';
import './style.css';

export default function App() {
  const Ho = (data) => {
    return () => {
      console.log('Something');
    };
  };

  return (
    <div>
      <h1>Hello StackBlitz!</h1>
      <p>Start editing to see some magic happen :)</p>
      <button onClick={Ho('data')}> Click</button>
    </div>
  );
}

Link -https://stackblitz.com/edit/react-mxcbvq?file=src/App.js

  • Related