Problem

This one is for the React heads.

React’s useRef hook allows you to persist values between renders, without triggering a re-render of the component. Using only React.useState, can you ~re-create the functionality of React.useRef.

Solution

The marketing pitch for React.useState is that it allows you to add state to function components. This is true, but we can break it down even further. Fundamentally, the useState Hook gives you two things - a value that will persist across renders and an API to update that value and trigger a re-render.

const [value, setValueAndReRender] = React.useState(
  'initial value'
)

When building UI, both are necessary. Without the ability to persist the value across renders, you’d lose the ability to have dynamic data in your app. Without the ability to update the value and trigger a re-render, the UI would never update.

Now, what if you had a use case where you weren’t dealing with any UI, so you didn’t care about re-rendering, but you did need to persist a value across renders? In this scenario, it’s like you need the half of useState that lets you persist a value across renders but not the other half that triggers a re-render — Something like this.

function usePersistentValue (initialValue) {
  return React.useState({
    current: initialValue
  })[0]
}

Spoiler alert, the functionality of our custom usePersistentValue Hook is very similar to the built-in React.useRef Hook.

If you want to add state to your component that persists across renders and can trigger a re-render when it’s updated, go with useState (or useReducer). If you want to add state to your component that persists across renders but doesn’t trigger a re-render when it’s updated, go with useRef.