Is it an anti-pattern to define a function component inside the render() function?

react anonymous function in render
function inside render react
anonymous function react
react inline function
react nested functions
react inline bind
react onclick performance
inline arrow function react

I want to know if it's an anti-pattern or if it affects the component somehow to do something like this:

render() {
  const MyFuncComponent = ({ prop1, prop2 }) => (
    // code here
  )

  return (
    <div>
      <MyFuncComponent prop1={something} prop2={else} />
    </div>
  )
}

I think in general people avoid defining functions in render but according to this blog post it is not neccesarily a bad practice. The blog post focuses on inline event handler functions being defined in render but I would guess it applies to any function defined in render. Defining functions in render means there is the overhead of redfining them each time render is called but that may not make a noticible performance difference depending on your component.

For the particular example you gave I would reccomend not to define another react component in render. If you do define any functions in render they should be cohesive to what render is doing. Defining another component or adding a bunch of functions inside of render can make in unwieldy and hard to understand what the code is doing.

Function as Child Components Are an Anti-Pattern, bind() and arrow functions in Components. You must have bound your custom functions in the constructor function before using them as props for  Using a pattern that goes against what we all consider to be a best practice is called an anti-pattern. By definition, then, FaCCs are an anti-pattern. Render Props. I’ll remind you that passing a render callback function to a component is not the issue. The issue is that the FaCC implementation chose to use the prop children.

Yes, this is an anti-pattern for the same reason we shouldn't use a Higher-Order-Component inside of render.

Don’t Use HOCs Inside the render Method

React’s diffing algorithm (called reconciliation) uses component identity to determine whether it should update the existing subtree or throw it away and mount a new one. If the component returned from render is identical (===) to the component from the previous render, React recursively updates the subtree by diffing it with the new one. If they’re not equal, the previous subtree is unmounted completely.

Normally, you shouldn’t need to think about this. But it matters for HOCs because it means you can’t apply a HOC to a component within the render method of a component:

render() {
  // A new version of EnhancedComponent is created on every render
  // EnhancedComponent1 !== EnhancedComponent2
  const EnhancedComponent = enhance(MyComponent);
  // That causes the entire subtree to unmount/remount each time!
  return <EnhancedComponent />;
}

The problem here isn’t just about performance — remounting a component causes the state of that component and all of its children to be lost.

This means that the new component will appear in the React tree (which can be explored with the react-devtools) but it won't retain any state and the lifecycle methods like componentDidMount, componentWillUnmount, useEffect will always get called each render cycle.

Solutions

Since there are probably reasons why we want to create a component dynamically, here's some common solutions to bypass the pitfalls.

Define the new component outside

Either in its own file, or directly above the parent component's definition.

const MyFuncComponent = ({ prop1, prop2 }) => <>{/* code here */}</>;

const MyComponent = props => (
  <div>
    {props.list.map(({ something, thing }) => (
      <MyFuncComponent prop1={something} prop2={thing} />
    ))}
  </div>
);
Helper function

A regular function that returns JSX can be defined and used directly inside another component. It won't appear as a new component inside React's tree, only its result will appear, as if it was inlined.

That way, we can also use variables from the enclosing scope (like props.itemClass in the following example) in addition to any other parameters you want.

const MyComponent = props => {
  // Looks like a component, but only serves as a function.
  const renderItem = ({ prop1, prop2 }) => (
    <li className={props.itemClass}> {/* <-- param from enclosing scope */}
      {prop1} {prop2} {/* other code */}
    </li>
  );

  return <ul>{props.list.map(renderItem)}</ul>;
};

It could also be defined outside the component since it's really flexible.

const renderItem = (itemClass, { prop1, prop2 }) => (
  <li className={itemClass}>
    {prop1} {prop2} {/* other code */}
  </li>
);

const MyComponent = props => (
  <ul>
    {props.list.map(item => renderItem(props.itemClass, item))}
  </ul>
);

But at that point, just define a React component instead of faking it with a function. Use React in a predictable manner and to its full potential.

Inline the logic

It's really common to inline JSX inside of a condition or a map callback.

const MyComponent = ({ itemClass }) => (
  <ul>
    {props.list.map(({ something, thing }) => (
      <li className={itemClass}>
        {something} {thing} {/* other code */}
      </li>
    ))}
  </ul>
);

How to NOT React: Common Anti-Patterns and Gotchas in React, When a React Component's method uses this , we need to be careful what and the method was defined without using an arrow function syntax, Clicking the button would work and log “Invoked from inside an anonymous function! constructor(props) but before render() , meaning invoking setState() in  Using an arrow function in render creates a new function each time the component renders, which may break optimizations based on strict identity comparison. Is it OK to use arrow functions in render methods? Generally speaking, yes, it is OK, and it is often the easiest way to pass parameters to callback functions.

Couple of questions before doing this:

  1. does it make code more readable? (it depends, let's say 50/50)
  2. does it make code more testable? (unable to be mocked, tight coupling - so "no")
  3. does it make code more flexible? (tight coupling - so "no" again)

I'd rather vote for making base component getting inner one through props. And that inner component is created somewhere outside. You'd get more flexibility, code'd be more readable because of abstraction, also with better testability.

React Gotchas, Anti-Patterns, and Best Practices - Steven Li, Anti-patterns are certain patterns in software development that are considered While rendering a list of similar components, keys help React identify which Most developers tend to define constant object literals and arrays inside the render methods in react. loadSomething().then(function(something) { The most obvious one difference is the syntax. A functional component is just a plain JavaScript function which accepts props as an argument and returns a React element. A class component requires

React Anti Patterns - Suraj KC, Fix this too-common pattern that can make your code difficult to read, change, and share. First, the Tabs component already has a render method. this kind of rendering functionality inside the component specifically because the tabs Now let's make this component a standalone functional component. This function is a valid React component because it accepts a single “props” (which stands for properties) object argument with data and returns a React element. We call such components “function components” because they are literally JavaScript functions. You can also use an ES6 class to define a component:

React Anti-pattern: renderThing - DEV Community ‍ ‍ , 1) Why Is This An "Anti-Pattern" in React??? Now let's see what the code might look like inside the <ContentArea> component: We have a simple render() function that's calling the next component below it in the hierarchy. to just view a given block of code and declare that it's somehow "bad" - even if  The term “render prop” refers to a technique for sharing code between React components using a prop whose value is a function. A component with a render prop takes a function that returns a React element and calls it instead of implementing its own render logic. Libraries that use render props include React Router, Downshift and Formik.

Why Is This An "Anti-Pattern" in React??? - DEV, A component with a render prop takes a function that returns a React element and you might try rendering the <Cat> inside <Mouse> 's render method, like this: “render props” you don't have to use a prop named render to use this pattern. problem, you can sometimes define the prop as an instance method, like so:. React components essentially comprises 3 things: state,props and markup (or other components). Props are immutable. However, the state is mutable. Changing the state causes the component to re-render. If the state is managed internally by the component, this.setState function is employed to update the state. There are a few important things to

Comments
  • I believe so. Usually in the render function you only put some calculated variables to reduce code in your JSX.
  • I don't think we should do that. By doing this, every time a state updates the function gets redefined.
  • @ArpitKapadia yeah that makes sense, thanks!
  • …and I'm pretty sure react won't notice that it's still the same component.