0
votes

This is a class component that is using state and setState, but i would like to use useState. Also, aside from being able to use a functional component rather than a class base component, what are the benefits?

    import React, {Component} from "react"

    class Toggler extends Component {
        state = {
            on: this.props.defaultOnValue
        }

        toggle = () => {
            this.setState(prevState => {
                return {
                    on: !prevState.on
                }
            })
        }
static 
    defaultProps = {
        defaultOnValue: false
    }

        render() {
            return (
                <div>
                    {this.props.render(this.state.on, this.toggle)}
               </div>
            )
        }
    }

    export default Toggler

So far...

    import React, {useState} from "react"

    function Toggler() {
        const [on, setOn] = useState(this.props.defaultOnValue)

        toggle = () => {
            setOn( {/* what should go here? */} )

        }
static 
    defaultProps = {
        defaultOnValue: false
    }

        return (
                <div>
                    {this.props.render(on, toggle)}
                </div>
            )
    }

    export default Toggler
1
Have you had a specific problem trying to convert it? And if you don't know what the benefits are, why do you want to convert it?jonrsharpe

1 Answers

1
votes

Toggling your state value is as simple as inverting the current value returned from useState.

Functional components receive the props passed to them as an argument, so no need to use this.props. Also, to set static properties on a functional component you can just set them on the function itself.

function Toggler(props) {
  const [on, setOn] = useState(props.defaultOnValue)
  const toggle = () => {
    setOn(!on)
  }
  return <div>{props.render(on, toggle)}</div>
}

Toggler.defaultProps = {
  defaultOnValue: false
}

export default Toggler

In terms of benefits, it's up to you to decide whether you think it's worth it for your case. There's no specific benefit to using useState rather than a class based component, however if you want to start using other hooks, or integrate with third party libraries using hooks, you may wish to convert some of your components to functional ones where necessary.