Pass setState from useState() hook using <Link>

Viewed 2796

I'm having a problem with react-router when trying to pass setState from the useState hook using <Link>. What am I doing wrong?

I created simple project to show the problem: https://codesandbox.io/s/restless-surf-mj2vx?fontsize=14

Open console and click on the link to see the error.

  const [state, setState] = useState(0);

  return (
    <div className="App">
      <Link to={{ pathname: "/test", state: { state, setState } }}>test</Link>
      <Switch>
        <Route path="/test" component={Test} />
      </Switch>
    </div>
  );
}

I'm getting this error that does not help me resolve the issue:

"Uncaught DOMException: Failed to execute 'pushState' on 'History': function () { [native code] } could not be cloned."

1 Answers

If you need the setState function in the <Test /> component, pass it with the route instead:

const [state, setState] = useState(0);

return (
    <div className="App">
        <Link to={{ pathname: '/test' }}>test</Link>
        <Switch>
            <Route
                path="/test"
                render={props => (
                    <Test {...props} state={state} setState={setState} />
                )}
            />
        </Switch>
    </div>
);
Related