DEV Community

Discussion on: React Style Guide

Collapse
 
javiergnz profile image
Javier Gonzalez Toro

i wonder what are the best way to ordering in react hooks, i came with this approach, but i don't know if are the best way...

import React, { useState, useEffect } from 'react'
// import other package, components, utils, styles, etc

const Wrapper = () => {
  // declare your variables, 
  const [foo, setFoo] = useState(null)
  const pathname = 'home'

  // declare you custom hooks, functions, etc
  const handleFoo = (bar) => {
    if (bar === 'something')  {
      setFoo(bar)
    }
  }

  // declare your useEffects, useCallback, etc
  useEffect = () => {
    console.log(`Hello ${foo}`)
  }, [foo]

  return (
    <div className="wrapper">
     {/* show stuff... */}
    </div>
  )
}

export default Wrapper
Enter fullscreen mode Exit fullscreen mode
Collapse
 
abrahamlawson profile image
Lawson

Well, I am also using that way. But usually it looks like :

constructor -> hooks (useEffect, useCallBack... ) -> other functions

// constructor
const [foo, setFoo] = useState(null)
const pathname = 'home'

// life cycles ( hooks ), others function ( such as event handlers,... )
const handleFoo = (bar) => {
    if (bar === 'something')  {
      setFoo(bar)
    }
  }

 useEffect = () => {
   console.log(`Hello ${foo}`)
 }, [foo]

// renders
return (
    <div className="wrapper">
     {/* show stuff... */}
    </div>
 )
Enter fullscreen mode Exit fullscreen mode

I think if you're comfortable with that approach, keep it :)

You can get more info : React Ordering