An Interest In:
Web News this Week
- April 23, 2024
- April 22, 2024
- April 21, 2024
- April 20, 2024
- April 19, 2024
- April 18, 2024
- April 17, 2024
When React Hooks "just clicked" in my head
A lot of people writing React think that when they initialize a variable, it's going to stay that way every time.
For instance, let's imagine a very simple React component.
const Demo = ()=>{ const name = 'Bob'; return <div>Hello: {name}</div>};
You might come away thinking that the name
variable will always be the same piece of memory no matter how many times the Demo
component is rendered.
In reality, React calls that Demo
function every time it renders the parent components that contain the Demo component.
Wait a second...
Yes, that means that name
is going to be a new variable every time Demo
is called (which is every time React needs to render it).
So, it's almost like each time Demo
is rendered, the name
property is born again. That realization is what helped make React Hooks click. Hooks lets you make name
immortal (for the life of the browser tab being open).
What if I wanted it to stay the same?
Well, that's what hooks were more or less invented for. Hooks predominantly are about allowing React devs to use simple functions to describe their creational patterns but to allow these functions to express stateful concerns.
Before hooks, you would have had to use a Class to describe a component that has state.
But with React Hooks like useRef
, you can say "hey React, would you mind keeping this variable around?"
K, but let me see this in action
Sure! Here's a demo that shows starts off showing how the Demo
component is essentially stateless and therefore the name
property can never be the same between renders.
If you follow along the comments in the code example below, you'll be able to uncomment the correct lines to show how you can inform React of which pieces you want it to keep the same between renders.
Original Link: https://dev.to/dgreene1/when-react-hooks-just-clicked-in-my-head-4hd3
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To