Functions in stateless components?

functional component
functional component react native
react extend functional component
react functional components helper functions
react functional components typescript
react native function
state in functional component react
stateless functional components should not use this

I'm trying to convert this cool <canvas> animation I found here into a React reusable component. It looks like this component would require one parent component for the canvas, and many children components for the function Ball().

For performance reasons it would probably be better to make the Balls into stateless components as there will be many of them. I'm not as familiar with making stateless components and was wondering where I should define the this.update() and this.draw functions that are defined in function Ball().

Do functions for stateless components go inside the component or outside? In other words, which of the following is better?

1:

const Ball = (props) => {
    const update = () => {
        ...
    }

    const draw = () => {
        ...
    }

    return (
       ...
    );
}

2:

function update() {
     ...
}

function draw() {
     ...
}

const Ball = (props) => {
    return (
       ...
    );
}

What are the pros/cons of each and are one of them better for specific use cases such as mine?

First thing to note is that stateless functional components cannot have methods, you shouldn't count on calling update or draw on a rendered Ball if it is a stateless functional component.

In most cases you should declare the functions outside of the component function so you declare them only once and always reuse the same reference. When you declare the function inside, every time the component is rendered the function will be defined again.

There are cases in which you will need to define a function inside the component to, for example, assign it as an event handler that behaves differently based on the properties of the component. But still you could define the function outside Ball and bind it with the properties, making the code much cleaner and making the update or draw functions reusable.

// You can use update somewhere else
const update (propX, a, b) => { ... };

const Ball = props => (
  <Something onClick={update.bind(null, props.x)} />
);

If you're using hooks, you can use useCallback to ensure the function is only redefined when one of its dependencies (props.x in this case) changes:

const Ball = props => {
  const onClick = useCallback((a, b) => {
    // do something with a, b and props.x
  }, [props.x]);

  return (
    <Something onClick={onClick} />
  );
}

This is the wrong way:

const Ball = props => {
  function update(a, b) {
    // props.x is visible here
  }

  return (
    <Something onClick={update} />
  );
}

When using useCallback, defining the update function in the useCallback hook itself our outside the component becomes a design decision more than anything, you should take into account if you're going to reuse update and/or if you need to access the scope of the component's closure to, for example, read/write to the state.

React Function Components, React Stateless Function Component​​ Every component we have seen so far can be called Stateless Function Component. They just receive an input as props and return an output as JSX: (props) => JSX . The input, only if available in form of props, shapes the rendered output. Stateless components are those components which don’t have any state at all, which means you can’t use this.setState inside these components. It is like a normal function with no render method. It has no lifecycle, so it is not possible to use lifecycle methods such as componentDidMount and other hooks.

We can have functions inside stateless functional components, below is the example:

 const Action = () => {
  function  handlePick(){
     alert("test");
  }
  return (
    <div>
      <input type="button" onClick={handlePick} value="What you want to do ?" />
    </div>
  );
}

But, it's not a good practice as function handlePick() will be defined every time when the component is called.

React: Class Component vs Functional Component, . They just receive an input as props and return an output as JSX: (props) => JSX . The input, only if available in form of props, shapes the rendered output. Functional components are just JavaScript functions. They take in an optional input which, as I've mentioned earlier, is what we call props. Some developers prefer to use the new ES6 arrow functions for defining components. Arrow functions are more compact and offer a concise syntax for writing function expressions.

We can use the React hook useCallback as below in a functional component:

const home = (props) => {
    const { small, img } = props
    const [currentInd, setCurrentInd] = useState(0);
    const imgArrayLength = img.length - 1;
    useEffect(() => {
        let id = setInterval(() => {
            if (currentInd < imgArrayLength) {
                setCurrentInd(currentInd => currentInd + 1)
            }
            else {
                setCurrentInd(0)
            }
        }, 5000);
        return () => clearInterval(id);
    }, [currentInd]);
    const onLeftClickHandler = useCallback(
        () => {
            if (currentInd === 0) {

            }
            else {
                setCurrentInd(currentInd => currentInd - 1)
            }
        },
        [currentInd],
    );

    const onRightClickHandler = useCallback(
        () => {
            if (currentInd < imgArrayLength) {
                setCurrentInd(currentInd => currentInd + 1)
            }
            else {

            }
        },
        [currentInd],
    );
    return (
        <Wrapper img={img[currentInd]}>
            <LeftSliderArrow className={currentInd > 0 ? "red" : 'no-red'} onClick={onLeftClickHandler}>
                <img src={Icon_dir + "chevron_left_light.png"}></img>
            </LeftSliderArrow>
            <RightSliderArrow className={currentInd < imgArrayLength ? "red" : 'no-red'} onClick={onRightClickHandler}>
                <img src={Icon_dir + "chevron_right_light.png"}></img>
            </RightSliderArrow>
        </Wrapper>);
}

export default home;

I'm getting 'img' from it's parent and that is an array.

Stateless Component vs Pure Component, all what it needs to do is just call MyStatelessComponent function and pass props there. That's it. Introduction. Stateless functional components are an awesome way to decouple complex architecture from the design of a component's output. You can remove the unnecessary bloat of complex logic and provide a simple presentational component that is easy to read and re-use. This opens the doors for more people to help with development and adding types with TypeScript makes it even easier!

2: is good, but it has a tragedy when you want to use props.

the best practice is useHooks functions, like useCallback function.

import they from react library.

React Stateless Functional Components: Nine Wins You Might Have , These components use plain JavaScript functions. Here's the As you can see above, the stateless component is just a function. Thus, all the  Notice the stateless component is written as a function. As cool as state is, you should always aim to make your components as simple and stateless as possible, so different components can be reused like Lego pieces, even if you don’t have immediate plans to reuse a component. The stateful ones should feel lucky to be so!

How I write React stateless functional components, A functional(a.k.a. stateless) component is just a plain javascript function which takes props as an argument and returns a react element. const  A stateless functional component is just a function that returns JSX. It's very simple but incredibly useful. There are two ways to create a stateless functional component. Both are similar and do the same thing, it's just a matter of conciseness.

Functional Components with React stateless functions and Ramda, If you do write JavaScript, stop bikeshedding and just use prettier! Back to the component. Why this style? Let's compare to alternatives. function. As we’ve just seen, when you see a stateless functional component, you know it’s simply a function that takes props and spits out HTML. Even if it contains a lot of markup and nested functions

React Hooks: A transition of functions from stateless to stateful , What is a React stateless function? Usually you may define a React component as follows: Or using the ES6 class syntax:  As we’ve just seen, when you see a stateless functional component, you know it’s simply a function that takes props and spits out HTML. Even if it contains a lot of markup and nested functions inside the render, it’s conceptually simple. It’s a pure function. This leads to the next big win…

Comments
  • Can you post the existing code so we see how it will get used?
  • @Scimonster I posted it in an embedded link, maybe you missed it. Here's the link: codepen.io/awendland/pen/XJExGv
  • Thanks Marco, that clears things up a bit. The thing I'm confused about in my case is related to the this.draw function inside the Ball. It uses the ctx from what would be the parent's <canvas> and also uses the this keyword for what would be the child Ball component. What would be the best way to integrate implement the stateless component so both of those properties are accessible?
  • there is no this when using stateless functional components, have that in mind. For the canvas context, you would have to pass it to every single Ball, that doesn't sound good at all.
  • So in this case it would be best to just have no child component you're saying?
  • @MarcoScabbiolo no no, that's not my case, already using arrow functions natively for quite a long time, since the only browser not supporting them is IE. Actually I managed to find this comment from one article where it's actually claimed that bind specifically in Chrome earlier than 59 was even slower than arrow functions. And in Firefox it's as well quite a while since they both perform with the same speed. So I'd say in such cases there is no difference what is the preferred way :)
  • @MauricioAvendaño either way works, but it is a bad practice for the Something component to know that there is a prop X in its parent component as it makes it aware of its context. The same happens for the question you're asking and the sample code I've written, it depends on the context, which is ignored for the sake of simplicity.
  • If its not a good practice, then what will be the alternate solution?
  • @JohnSamuel The alternative is to define handlePick() above/outside the component like function handlePick() { ... }; const Action = () => { ... } the result being that handlePick is only defined once. If you need data from the Action component, you should pass it as parameters to the handlePick function.
  • if this is not a good practice you could have added the good practice with the answer? now i have to search again for the good practice :(
  • can you give an example of using hook for method inside functional component? (not set state method)