Converting React Components to use Hooks (useEffect and useState)

This isn’t a finished article, it’s a work in progress. I’m learning React Hooks, so there may be factually inaccurate information below. Let me know if you know that to be the case!

Functional Stateless Components are prerequisite learning to Hooks.

Functional components are a function that accepts props and returns a React component.

// a class component
export default class Footer extends React.Component {

 render(){
    const {props} = this;
    return <Text>Hi {props.name}</Text>
 }
}

// a functional component
const Footer = (props) => {
  return <Text>Hi {props.name}</Text>
}
export default Footer

Hooks extend this simple model with the ability to manage state (via useState) and manage side-effects (via useEffect).

useState accepts an initial state (that is only used on load) and returns both the current state and a state modifier function, for further state changes. It’s easier than it sounds:

const initialState = {
  sidebarVisible: false
}
const SidebarComponent = (props) => {
  // initialState will be used to populate currentStatre.
  const [currentState, setState] = 
  useState(initialState)

  // we can use setState from above to change the state now, when the user clicks open.
  openClicked = () => {
    setState({...state, sidebarVisible: true})
  }

  return state.sidebarVisible && <View><Text>Something here</Text></View>
}

useEffect accepts an anonymous function to execute the side effects, and a watched array of parameters. Side effects are pretty much any code that runs based on changes that does not instantly update the UI (API calls etc).

useEffect(() => {
  // fetch some data
  api.users.get(props.id)
}, [props.id])
// the side effect will run when props.id changes.

It’s hard (/mentally taxing) to refactor from old class components to functional components and change the lifecycle methods to useEffect/useState all at the same time. I’m not sure I’d refactor a codebase to this style for the sake of it.

I’m also interested to see the effect when writing new code in this style, rather than refactoring over to it. It’s a totally different lifecycle consideration and I think the code would be completely different.