React redirection on a function without a render method

You can't use history.push({}) from a React function component (without a render method).

Example:

jsx
import { useHistory } from 'react-router-dom'

// ❌ "useHistory" is called in function "sum" that is neither a React function component nor a custom React Hook function
const sum = (x, y) => {

    const history = useHistory()

    let res = x + y

    history.push({ pathname: `/${res}` })

}

However, you can use a simple JavaScript redirect via window.location.

Example:

jsx
const sum = (x, y) => {

    let res = x + y

    window.location = `/${res}`

}

Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.