DEV Community 👩‍💻👨‍💻

Cover image for React - Stateless function
Sandro Jhuliano Cagara
Sandro Jhuliano Cagara

Posted on • Updated on

React - Stateless function

Stateless functions are a brilliant way to define highly reusable components. They don't hold state; they're just functions.

const MyExample = () => <div>Hello World!</div>
Enter fullscreen mode Exit fullscreen mode

They get passed props and context.

const MyExample = (props, context) => {
    return <div style={{color: context.color}}>Hi {props.name}</div>
}
Enter fullscreen mode Exit fullscreen mode

They can define local variables, where a function block is used.

const MyExample = (props, context) => {
    const style = {
        fontWeight: "bold",
        color: context.color,
    }

    return <div style={style}>{props.name}</div>
}
Enter fullscreen mode Exit fullscreen mode

But you could get the same result by using other functions.

const getStyle = context => ({
    fontWeight: "bold",
    color: context.color,
})

const MyExample = (props, context) => {
    return <div style={getStyle(context)}>{props.name}</div>
}
Enter fullscreen mode Exit fullscreen mode

They can have defined defaultProps, propTypes and contextTypes.

MyExample.propTypes = {
    name: PropTypes.string.isRequired
}

MyExample.defaultProps = {
    name: "Guest"
}

MyExample.contextTypes = {
    color: PropTypes.string
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

In defense of the modern web

I expect I'll annoy everyone with this post: the anti-JavaScript crusaders, justly aghast at how much of the stuff we slather onto modern websites; the people arguing the web is a broken platform for interactive applications anyway and we should start over;

React users; the old guard with their artisanal JS and hand authored HTML; and Tom MacWright, someone I've admired from afar since I first became aware of his work on Mapbox many years ago. But I guess that's the price of having opinions.