Hi, Everyone, hope you are doing great !
Today, I’ll explain you all the learnings I’ve gained from implementing State Management in react, Honestly when I started it felt very hard and confusing at the same time, if Everything works fine without it why should i even waste my time learning it, but then I found something very interesting.
In react every time you’ll try to create a web component, you’ll need to pass some props let’s a react card component for a user you’ll need userName, Age, more data… and usually I would do -
const Card = ({name, age, etc..})=>{
return (
<>
content
</>
)
}
and will define state variables to utilise this reusable code. But did you know that every time a state changes the whole app will render.
What’s a render ?
Alright so When the state of your variable changes/ value in short. The browser will re-render the whole component which means wastage to CPU, which ultimately will lead to performance downsides.
But Don’t worry my friend, I’ve something for you.
State Management : It won’t just help you manage your props but also will help you optimize the re-renders in your react web components.
Steps to work with Recoil
Install the library
create a seperate folders for Atoms and Selectors. (We’ll come to this).
import your first atom from recol library
Now what the heck is an Atom ?
Consider a JS object which could hold a state variable or could become a state variable without actually defining a built in hook.
Let’s understand it from Syntax
So, this atom will hold to properties a key which makes it unique and a default value let’s say 0 in our case.
Now we have our atom, we need some built in hooks to extract the values from the Atom :
Now, we see two hooks here :
useRecoilValue : consider it as something which will help us get the value of the atom. in our case it was 0 later we can update by using useSetRecoilState();
In the Beginning it might sound very hard but if carefully see it very similar to useState() with a value and a function.
Now you are ready to implement