This content originally appeared on DEV Community and was authored by Dan Greene
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.
This content originally appeared on DEV Community and was authored by Dan Greene
Dan Greene | Sciencx (2021-05-19T20:43:08+00:00) When React Hooks “just clicked” in my head ??. Retrieved from https://www.scien.cx/2021/05/19/when-react-hooks-just-clicked-in-my-head-%f0%9f%92%a1%f0%9f%a4%a9/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.