1

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.

1
  • Lazy initial state is the reason the initial state is the return value. You already saw that's what it was doing, but I wanted to call out the intended purpose. Commented Apr 2, 2020 at 19:56

2 Answers 2

5

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!");
  }
})
Sign up to request clarification or add additional context in comments.

Comments

1

Create a const function, which returns a function

const fn = () => () => {};
const [func, setFunc] = useState(fn);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.