I'm using function components. I am using useRef to store a previousValueCount because I don't want it to rerender the component when it updates. This works perfect as long as my useRef declaration is in the component that my code reads and writes with that ref in. However, realizing I may need this higher up the tree, I turned to props. However, when I moved the useRef declaration to the parent and passed the ref as a prop, the code seemed to break, telling me it was null, regardless of the initialization value and it working before in child. To my understanding I could not pass ref as prop so I turned to React.forwardRef. I tried the same thing with no solution and a similar error shared below. How can I pass a ref as a prop or down component tree?
APP COMPONENT:
function App() {
const [itemsLeftCount, setItemsleftCount] = useState(0);
return (
<ToDos
itemsLeftCount={itemsLeftCount}
setItemsLeftCount={setItemsLeftCount}
></ToDos>
)
}
PARENT COMPONENT:
function ToDos(props) {
const prevItemsLeftCountRef = useRef(0);
return (
<ToDoBox
itemsLeftCount={props.itemsLeftCount}
setItemsLeftCount={props.setItemsLeftCount}
ref={prevItemsLeftCountRef}
></ToDoBox>
{
CHILD COMPONENT:
const ToDoBox = React.forwardRef((props, ref) => {
useEffect(() => {
//LINE 25 Error points to right below comment
ref.prevItemsLeftCountRef.current = props.itemsLeftCount;
}, [props.itemsLeftCount]);
useEffect(() => {
//ON MOUNT
props.setItemsLeftCount(ref.prevItemsLeftCountRef.current + 1);
//ON UNMOUNT
return function removeToDoFromItemsLeft() {
//this needs to only run after setitemsleftcount state is for sure done updating
props.setItemsLeftCount(ref.prevItemsLeftCountRef.current - 1);
};
}, []);
})
I receive this error: Uncaught TypeError: Cannot read properties of null (reading 'prevItemsLeftCountRef') at ToDoBox.js:25:1
@Mustafa Walid
function ToDos(props) {
const prevItemsLeftCountRef = useRef(0);
const setPrevItemsLeftCountRef = (val) => {
prevItemsLeftCountRef.current = val;
};
return (
<ToDoBox
itemsLeftCount={props.itemsLeftCount}
setItemsLeftCount={props.setItemsLeftCount}
prevItemsLeftCountRef={prevItemsLeftCountRef}
setPrevItemsLeftCountRef={setPrevItemsLeftCountRef}
></ToDoBox>
)
}
function ToDoBox(props) {
useEffect(() => {
//itemsLeftCount exists further up tree initialized at 0
props.setPrevItemsLeftCountRef(props.itemsLeftCount);
}, [props.itemsLeftCount]);
}