My concerns with React hooks

import React from 'react';function Foo(props) {
return (
<div>
Hey {props.name}, this is a functional component.
</div>
);
}
class Bar extends React.Component {
render() {
return (
<div>
Hey {this.props.name}, this is a class component.
</div>
);
}
}
import React from 'react';

class TodoList extends React.Component {
constructor(props) {
super(props);

this.state = {
todos: [
{
done: false,
label: 'Do something'
}
]
};
}

onToggleTodo(index) {
this.setState(({ todos }) => ({
todos: todos.map((todo, todoIndex) => {
if (todoIndex === index) {
return {
...todo,
done: !todo.done
};
}

return todo;
})
}));
}

render() {
return (
<ul>
{this.state.todos.map((todo, index) => (
<li key={index}>
<input
type="checkbox"
onChange={() => this.onToggleTodo(index)}
checked={todo.done}
/>
{todo.label}
</li>
))}
</ul>
);
}
}

A new type of component: hooks

import React from 'react';

function TodoList(props) {
const [todos, setTodos] = React.useState([
{
done: false,
label: 'Do something'
}
]);

const onToggleTodo = index => {
setTodos(currentTodos =>
currentTodos.map((todo, todoIndex) => {
if (todoIndex === index) {
return {
...todo,
done: !todo.done
};
}

return todo;
})
);
};

return (
<ul>
{todos.map((todo, index) => (
<li key={index}>
<input
type="checkbox"
onChange={() => onToggleTodo(index)}
checked={todo.done}
/>
{todo.label}
</li>
))}
</ul>
);
}
Guys, is it me or there’s something weird with those hooks?
function Bar(props) {
const [todos, setTodos] = React.useState([]);

if (props.filter) {
// This is impossible
const
[filter, setFilter] = React.useState(null);
}
}
import React from 'react';
import useUserQuery from './useUserQuery';

function UserProfile(props) {
if (props.userID) {
return useUserQuery(props.userID, user => (
<div>{user.displayName}</div>
));
}

return <div>Anonymous</div>;
}
import React from 'react';
import LoggedInUserProfile from './LoggedInUserProfile';

function UserProfile(props) {
if (props.userID) {
return <LoggedInUserProfile userID={props.userID} />;
}

return <div>Anonymous</div>;
}
import React from 'react';class Foo extends React.Component {
componentDidMount() {
console.log('Foo is mounted');
}

componentDidUpdate() {
console.log('Foo is updated');
}

render() {
return <div />;
}
}
import React from 'react';function Bar() {
React.useEffect(() => {
console.log('Foo is mounted');
}, []);

React.useEffect(() => {
console.log('Foo is udpated');
});

return <div />;
}

React is becoming less intuitive and declarative, making it harder to understand.

But I’m probably wrong

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store