Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React - stateless component, function inside or outside component

I want to ask. Where should I define function in React stateless component?

For example:

I want to prepare function to call it with some parameters, but I want to avoid create new one after re-render.

Pseudocode:

    const example = (params) => {...}

    const statelessComponent = () => {
        return(
             <button onClick={example(params)}
        )
    }

or

    const statelessComponent = () => {
        const example = (params) => {...}

        return(
             <button onClick={example(params)}
        )
    }

but I also want to avoid:

  • calling function while render
  • I don't want to use "useCallback" hook to prevent create new reference.

If only one solution is to create function in Parent component and send it via props to Children component and after that call this function ?

Can someone explain me, how to do it with the best performance without useCallback or useMemo hooks?

Thank you.

like image 811
frontreact Avatar asked Nov 11 '19 21:11

frontreact


People also ask

Can stateless components have functions?

A stateless function component is a typical React component that is defined as a function that does not manage any state. There are no constructors needed, no classes to initialize, and no lifecycle hooks to worry about. These functions simply take props as an input and return JSX as an output.

Are functional components in React stateless?

A functional component is always a stateless component, but the class component can be stateless or stateful. There are many distinct names to stateful and stateless components.

Can we use render () inside functional component?

There is no render method used in functional components. With functional components there are fewer lines of code another positive to this is that the fewer lines of code a developer has to read and write, the faster and easier their code is to comprehend.

How is stateless component different from a stateful component?

Stateful and Stateless Components In React, a stateful component is a component that holds some state. Stateless components, by contrast, have no state. Note that both types of components can use props. In the example, there are two React components.

What are stateless functional components in react?

Stateless functional components in React are pure functions of the passed in props. These components do not rely on state and discard the use of component lifecycle methods. You may, however, still define propTypes and defaultPropts.

Is react stateless or stateless?

In idiomatic React code, most of the components you write will be stateless, simply composing other components. We’re introducing a new, simpler syntax for these components where you can take props as an argument and return the element you want to render.

What is state in react?

First, let’s review what state is. In a component, state is data we import — typically to show the user — that is subject to change. It could change because the database we’re getting from may be updated, the user modified it — there are so many reasons that data changes!

What are stateful props in react?

One of the most common programming patterns in React is to use stateful parent components to maintain their own state and pass it down to one or more stateless child components as props. The example code shows a basic example.


Video Answer


1 Answers


2021 edit:


After implementation of React Hooks, the issue is no longer relevant - you can declare functions inside your functional component as long as you want. However if you want to avoid children re-render, you can wrap your functions with useCallback hook so the function instance remains between renders.

const handleChange = useCallback(() => /* do stuff */, []);

https://reactjs.org/docs/hooks-reference.html#usecallback


Old answer:


I would suggest to keep your functions outside the Stateless Components as long as it's possible.

Consider following example. Your parent component re-renders, so the SFC child does (FYI: SFC re-renders everytime parent re-renders, it doesn't have any built-in shallow props comparison logic).

If you declare function inside SFC, it will create a completely new instance with every re-render.

If you declare function outside SFC, it will be used n-times, but the function itself will remain the same instance.

Working example at StackBlitz: https://stackblitz.com/edit/react-1m2hds

How to test it - write something inside input, then click on the child. Parent will re-render, so the child does. The outside-box function fn1 gets pushed to window variable test1, the inside-box function fn2 goes into test2. Now repeat process. If you compare functions inside test1 -> test1[0] === test1[1] will return true, since both of the functions are the same instance.

If you compare test2[0] === test2[1] it will return false, because new instance of function was created.

Note: Use built-in StackBlitz console for testing purposes.

Final note: regardless of what been told above, the perfomance differences are basically unnoticeable.

window.test1 = [];
window.test2 = [];

class App extends Component {
  state = {
    name: 'React'
  };

  handleChange = (e) => this.setState({ name: e.target.value });

  render() {
    return (
      <div>
        <Child name={this.state.name} />
      </div>
    );
  }
}

const fn1 = () => {};

const Child = ({ name }) => {
  const fn2 = () => {};
  const checkout = () => {
    window.test1.push(fn1);
    window.test2.push(fn2);
  }

  return (
    <div onClick={checkout}>{name}</div>
  );
}
like image 198
kind user Avatar answered Oct 29 '22 00:10

kind user