How do I define methods in stateless components?

I am hesitant to give a solution to this because inline Stateless Functions are not supposed to have methods. if you want a method you should use a Class and theres nothing wrong with using a class. Its all based on what you need to do. Stateless Functions are designed to be a super light weight way to render something that doesn’t need methods, or a state or even a this context (in terms of a class).

you should be doing it like this.

class App extends Component {
    constructor(){
        super();
        // note this is a Stateless Component because its a react class without a state defined.
    }
    renderList = () => {
        return <span>Something Here</span>;
    }
    render() {
        return <div>{this.renderList()}</div>
    }
}

a HACK way that I wouldn’t recommend (but does solve your question in the way you want it to) would be like this.

const App = () => {
    let renderList = () => {
        return <span>Something Here</span>
    }
    return <div>{renderList()}</div>
}

The reason why its generally a bad practice is because you are creating a function and all the memory allocation needed every render cycle. Subsequently, the internal diffing optimizations that react provides is generally useless if you do this because a new function gives a different signature than the prior render cycle. If this had a lot of children, they would all be forced to re-render!

Edit – React Version 16.8.0 +

You can use Hooks to do this. I would recommend using memo to memoize the function, this way you aren’t creating it in memory each render cycle.

const RenderList = React.memo(props => (
  <span>Something Here</span>
))

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)