Not every component is going to modify a 'global' state stored in a Recoil atom - in some cases a component just needs to be able to read the value.
In this quick lesson we're going to learn how to use a
useRecoilValue hook to ensure that a component will be able to read a number stored in a Recoil atom in a read-only fashion.
Tomasz Lakomy: [0:00] We have a small counter app example. This app is using a single atom, which is called numState, in order to share the state between the Counter and the Display component. The counter is this button over here and the counter is that read-only value.
[0:13] There's a difference between those two components because in the Counter, we are using both number and setNumber from the useRecoilState, whereas in Display, we are not using the setNumber. Instead, we are just displaying this value.
[0:24] In that case, instead of using the useRecoilState hook, we can go ahead and import useRecoilValue and use it over here. Instead of this, I'm going to useRecoilvalue. We are not going to get the setNumber. Instead, we're just going to get the number. If I save that, we can see that our app still works fine.
[0:43] To recap, if you have a component that is just going to read the value stored within an atom, instead of using the useRecoilState, it is a better approach to use the useRecoilValue hook.