Bits and Pieces

Insightful articles, step-by-step tutorials, and the latest news on full-stack composable software development

Follow publication

React.useRef and React.createRef: The Difference

React.createRef and React.useRef

Example: browsing through shared React components ib bit.dev
class App extends React.Component {
componentDidMount() {
this.divRef = React.createRef()
}
render() {
return (
<div>
<div id="divR" ref={this.divRef}>App, here</div>
</div>
)
}
}
divRef.current instanceof HTMLDivElementtrue
function App {    const divRef = React.useRef()    return (
<div>
<div id="divR" ref={divRef}>App, here</div>
</div>
)
}
function App {    const divRef = React.useRef()
const valueRef = React.useRef(90)
return (
<div>
Value: {valueRef.current}
<div id="divR" ref={divRef}>App, here</div>
<button onClick={()=> valueRef.current = 88}>Incr</button>
</div>
)
}
function App {    const divRef = React.useRef()
const valueRef = React.useRef(90)
const [,setDummyState] = useState()
return (
<div>
Value: {valueRef.current}
<div id="divR" ref={divRef}>App, here</div>
<button onClick={()=> (valueRef.current = 88, setDummyState({}))}>Incr</button>
</div>
)
}
function App {    const valueRef = React.createRef()
const [,setDummyState] = useState()
return (
<div>
Value: {valueRef.current}
<button onClick={()=> (valueRef.current = 88, setDummyState({}))}>Incr</button>
</div>
)
}
App()let props = {
name: "nnamdi",
age: 90
}
App(props)
// mounting
const appInstance = new App(props, context)
// constructor is called and ref is created
appInstance.componentWillMount()
appInstance.componentDidMount()
// re-rendering
if(appInstance.shouldComponentUpdate())
appInstance.componentWillMount()
appInstance.componentDidMount()

Conclusion

Learn More

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Published in Bits and Pieces

Insightful articles, step-by-step tutorials, and the latest news on full-stack composable software development

Written by Chidume Nnamdi 🔥💻🎵🎮

JS | Blockchain dev | Author of “Understanding JavaScript” and “Array Methods in JavaScript” - https://app.gumroad.com/chidumennamdi 📕

Responses (3)

Write a response