Hacker News new | ask | show | jobs
by waddlesworth 2251 days ago
I've read about Hooks for awhile, but they still confuse me. Maybe it's largely because I haven't experienced any of the pain points that are described as the motivation for their development, but I've used a number of state-management libraries that handle state.

Just as one example, in a lot of posts and commentary I've seen, is that hooks are replacements for both HoCs and render props.

Admittedly, I haven't yet tried to do any actual development with hooks, but I can't even figure out how to solve the problem in the example in docs for HoCs[0].

Do you pass in a hook as a prop? That doesn't seem wise. A custom hook for each data source still has the same code duplication.

The docs talk a lot about how to build individual components using hooks, but very little about tying them together.

[0]: https://reactjs.org/docs/higher-order-components.html

1 comments

Hooks solve a couple different problems:

- Giving function components the ability to have internal state and trigger side effects, giving them the same capabilities as class components have had

- Reusing logic across components

I talked about the progress from mixins to HOCs to render props to hooks in a talk at ReactBoston last year [0], which had an example of tracking mouse coordinates using all four approaches. In that sense, yes, they do replace the other techniques as a way to reuse logic.

You call them inside of your function components, like this:

    function MyComponent() {
        const [counter, setCounter] = useState(0);
        const {x, y} = useMousePosition();

        // rest of the rendering logic here
    }


[0] https://blog.isquaredsoftware.com/2019/09/presentation-hooks...