ahahaha React shooting itself in the foot: useRef and useImperativeHandle
And here we are onto part 5B with props.children, useRef and useImperativeHandle.
props.children
It’s pretty simple actually, so far we’ve been using self closing tags for our own components like so:
<Togglable buttonLabel='show notes' />
But you can actually use the component as a wrapper as well like so:
<Togglable buttonLabel='show notes'>
<Note notes={notes}>
</Togglable>
Now, within the Togglable component, the data it’s wrapping around can be accessed with props.children. This is great, because Togglable is actually a wrapper that shows or hides what is passed into it as props.children. While we could have done a simple visible/hidden button with logic that returns the element or doesn’t on click, this makes the code re-usable and cleaner to look at.
useRef
It’s basically useState but changing it doesn’t cause a page rerender. Honestly I don’t really know what to use it for except for using it for timers or what FSO did.
useImperativeHandle
In React, you are only able to pass data down from parent to child with props. But then what if I wanted to toggle close a component from the parent? Well, in React there’s lifting the state up. But that can get messy, VERY fast (see: my attempt at making a React app with the basics)
React, being the incredible component and state first language it is, has this amazing roundabout bandaid fix for this situation, introducing…
useImperativeHandle, where you can pass things within a child back up to its parents. Like so:
useImperativeHandle(ref, () => {
return (thing to pass into ref)
})
Whatever that is returned from the function within useImperativeHandle is passed into the ref argument. It’s important to note that useImperativeHandle only accepts a ref variable as an argument as well. So, in a situation like this:
// Parent
const someRef = useRef('')
return (
<Component ref={someRef} />
)
// Child
const childVar = true
useImperativeHandle(props.ref, () => {
return childVar
})
The someRef.current in the parent will become true.
Note: You’ll have to wrap the props imports with forwardRef if you’re using React 18 instead of 19. See more about forwardRef here.
| Previous Post | Next Post |