Reputation: 5304
what is the syntax to assign to a variable an arrow function using react setState hook?
if I try something like this the function is just called an what that is return assigned:
const [func, setFunc] = useState(() => {});
here func will get 'undefined' because nothing is returned from that arrow function.
I need this because I need to call a function implemented on a Child element from event on the Parent - so maybe I can pass an empty function to the child and on mounting of the child use setFunc to update the implementation of func(and I need to do this because I have to update the child's state on parent's event).
something like this: https://codesandbox.io/s/react-update-child-from-parent-51rr8
import React, { useState, useEffect } from "react";
const Child = props => {
var lines = [];
useEffect(() => {
// equilavent to componentDidMount
props.setFunc(() => {
lines.push(lines.length);
console.log("'lines' updated!");
});
}, []);
return null;
};
const App = () => {
const [func, setFunc] = useState(() => {});
return (
<div>
<div onClick={func}>
click me to update 'lines' on child
</div>
<Child setFunc={setFunc} />
</div>
);
};
its almost working - i just need a little help.
Upvotes: 1
Views: 2695
Reputation: 85221
If you pass a function into useState
, react will call that function on the first render and use its return value as the initial value of the state. This feature is useful for performance if the initial value is expensive to compute.
That makes your life a bit more complicated, but you can still do what you want. You'll just use a function that returns a function. That second function becomes the initial value.
const [func, setFunc] = useState(() => () => {});
When you set the function you'll also need to do some extra work, because when you pass a function to setFunc, react is going to call that function and pass in the previous value. So as before, you need a function that returns a function, with the latter function being the new value.
props.setFunc((previous) => {
return () => {
lines.push(lines.length);
console.log("'lines' updated!");
}
})
Upvotes: 5
Reputation: 8135
Create a const function
, which returns a function
const fn = () => () => {};
const [func, setFunc] = useState(fn);
Upvotes: 1