Use useRecoilValue Hook to Read a Value From a Recoil Atom

Tomasz Łakomy
InstructorTomasz Łakomy
Share this video with your friends

Social Share Links

Send Tweet
Published 4 years ago
Updated 3 years ago

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.

egghead
egghead
~ 45 minutes ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today