Recommended way of importing React
There are a bunch of ways to import [[React]]. Below are all the valid formats of importing
useState
from React. They have all been used at different times throughout the history of React. Read [[Kent C. Dodds]]'s blog post below if you want to read a great summary of the differences.// global
window.React.useState()
// CommonJS
const React = require('react')
React.useState()
// ESModules default import
import React from 'react'
React.useState()
// ESModules named import
import { useState } from 'react'
useState()
// ESModules namespace import
import * as React from 'react'
React.useState()
Since React 17 was released we don't need to import React explicitly because of the new [[JSX]] transform. This means that only the final two formats above are needed today.
I would recommend using the last format, the namespaced import, with some of the benefits being
No need to update the import every time we need something else, like
useEffect
or useReducer
.Namespaced versions of the hooks are immediately obvious where they came from. Maybe you are also importing a custom
useState
hook. Down the line it will be easier to maintain because you don't need to look up which of the hooks you have imported.import * as React from 'react'
import Auth from './auth'
React.useState()
Auth.useState()
To make it easier to type I would recommend adding a snippet for it in your [[IDE]]. Here's my snippet which you can copy to [[Ultisnips]] or [[VS Code]].
[[Kent C. Dodds]]. Importing React Through the Ages. Link